I'm trying to use ltree
extension in PostgreSQL to build a full-text address search engine.
My model looks like this (it's slightly simplified):
from django.db import models
class Addresses(models.Model):
name = models.CharField(max_length=255)
path = models.CharField(max_length=255)
So, 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 do a full-text search on the aggregated name of each entity. Basically I need to convert each row in table to the next format 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'm doing that in such way, so user can perform queries like 'los ang cali' or similar. I have no problems to do that with 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;
That works fine, but while using RawQuerySet, I can't use things like .filter()
, .group_by()
, pagination, etc.
The main constraint to reproduce it in Django is this JOIN:
JOIN "Addresses" AS a ON (a.path @> s.path)
it's used to join all ancestors of each element and then aggregate them using array_agg()
, array_to_string
functions, so the output of these functions can be used further in full-text search.
If anyone have better ideas how to implement such kind of thing using Django ORM, please advise.