Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django search using Search Vector using multiple words or partial words

For search I want to use the search vector from PostgreSQL;

I wrote a custom query method:

  def search(self, text):

        search_vectors = (
            SearchVector('name', weight='A', config='english') +
            SearchVector('short_description', weight='B', config='english') +
            SearchVector('description', weight='C', config='english')
        )
        search_query = SearchQuery(text)
        search_rank = SearchRank(search_vectors, search_query, weights=[0.2, 0.4, 0.6, 1])

        return self.annotate(rank=search_rank).filter(rank__gte=0.2).order_by('-rank').

There are 2 'issues'. For example for the name 'Eric', if I search:

  • 'eric' I get the correct results
  • 'eric john' I get not result
  • 'eri' I get no results

I kind of understand why it fails, but I don't how to implement the fixes.

like image 617
user3541631 Avatar asked Mar 01 '26 05:03

user3541631


1 Answers

If I understand correctly, you want to have a partial search Well, for this, it is enough for you to paste from * to the end of the query and send it and you will find the results.

.
.    
search_query = SearchQuery(text + '*')
.
.

Of course, if you want to include the user's query, you can put query between two * as below and send it.

.
.
search_query = SearchQuery('*' + text + '*')
.
.

To know how it works read the following answer https://stackoverflow.com/a/44382089/16829292

like image 180
Amin Zayeromali Avatar answered Mar 03 '26 19:03

Amin Zayeromali