How to use tsvector field to perform ranking in Django with full-text postgresql search?

I need to execute a ranking query using the full-text search function postgresql and Django with a module django.contrib.postgres.

According to the doc , this is pretty easy to do using the class SearchRankby doing the following:

>>> from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
>>> vector = SearchVector('body_text')
>>> query = SearchQuery('cheese')
>>> Entry.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank')

This probably works well, but it’s not exactly what I want, since I have a field in my table that already contains the data that I would like to use (instead of recalculating the tsvector in each search query).

Unfortunately, I cannot figure out how to provide this tsvector field to a class SearchRankinstead of an object SearchVectorin a raw data field .

Can anyone point out how to deal with this?

Edit : Of course, just trying to create an instance SearchVectorfrom the tsvector field does not work and does not work with this error (something like I translated it from French):

django.db.utils.ProgrammingError: ERROR: to_tsvector (tsvector) function does not exist

+4
source share
1 answer

If your model has SearchVectorFieldthis:

from django.contrib.postgres.search import SearchVectorField

class Entry(models.Model):
    ...
    search_vector = SearchVectorField()

would you use F expression:

from django.db.models import F

...
Entry.objects.annotate(rank=SearchRank(F('search_vector'), query)).order_by('-rank')
+7
source

Source: https://habr.com/ru/post/1666002/


All Articles