0

I have a app that lets the user search a database of +/- 100,000 documents for keywords / sentences.

I am using Django 1.11 and the Postgres FullTextSearch features described in the documentation

However, I am running into the following problem and I was wondering if someone knows a solution: I want to create a SearchQuery object for each word in the supplied queryset like so:

query typed in by the user in the input field: ['term1' , 'term2', 'term3']

 query = SearchQuery('term1') | SearchQuery('term2') | SearchQuery('term3')
 vector = SearchVector('text')
 Document.objects.annotate(rank=SearchRank(vector, query)).order_by('-rank').annotate(similarity=TrigramSimilarity(vector, query).filter(simularity__gt=0.3).order_by('-simularity')

The problem is that I used 3 terms for my query in the example, but I want that number to be dynamic. A user could also supply 1, or 10 terms, but I do not know how to add the relevant code to the query assignment.

I briefly thought about having the program write something like this to an empty document:

for query in terms:
   file.write(' | (SearchQuery( %s )' % query ))

But having a python program writing python code seems like a very convoluted solution. Does anyone know a better way to achieve this?

Jasper
  • 2,131
  • 6
  • 29
  • 61

1 Answers1

1

Ive never used it, but to do a dynamic query you can just loop and add.

compound_statement = SearchQuery(list_of_words[0])
for term in list_of_words[1:]:
    compound_statement = compound_statement | SearchQuery(term)

But the documentation tells us that

By default, all the words the user provides are passed through the stemming algorithms, and then it looks for matches for all of the resulting terms.

are you sure you need this?

krs
  • 4,096
  • 19
  • 22
  • Thanks for your response! I think I may be misunderstanding the documentation. The examples there seemed to specify separate SearchQuery Objects, joined with '|'s for OR statements. Am I correct in understanding that instead of that, I could just supply a list to a single SearchQuery object and It would have the same effect? – Jasper Mar 14 '18 at 23:38