I am trying to use the ltree extension in PostgreSQL to create a full-text search engine.
My model looks like this (itβs a bit simplified):
from django.db import models class Addresses(models.Model): name = models.CharField(max_length=255) path = models.CharField(max_length=255)
So, the data in this table will look like this:
id | name | path ---------------------------- 1 | USA | 1 2 | California | 1.2 3 | Los Angeles | 1.2.3
I want to perform a full-text search on the aggregated name of each object. Basically I need to convert each row into a table in the following format in order to do a search:
id | full_name | path ------------------------------------------------- 1 | USA | 1 2 | California USA | 1.2 3 | Los Angeles California USA | 1.2.3
I do it this way, so the user can execute queries like "los ang cali" or the like. I have no problem doing this with a raw PostgreSQL query:
SELECT *, ts_rank_cd(to_tsvector('english', full_address), query) AS rank FROM (SELECT s.id, s.path, array_to_string(array_agg(a.name ORDER BY a.path DESC), ' ') AS full_address FROM "Addresses" AS s INNER JOIN "Addresses" AS a ON (a.path @> s.path) GROUP BY s.id, s.path, s.name ) AS subquery, to_tsquery('english', %s) as query WHERE to_tsvector('english', full_address) @@ query ORDER BY rank DESC;
This works fine, but when using RawQuerySet I cannot use things like .filter() , .group_by() , pagination, etc.
The main limitation for playing in Django is JOIN :
JOIN "Addresses" AS a ON (a.path @> s.path)
he used to combine all the ancestors of each element, and then grouped them using the array_agg() , array_to_string , so the output of these functions can be used further in full-text search .
If anyone has ideas on how to implement such things using Django ORM , please let me know.