Bryden Fogelman
Bryden Fogelman

Reputation: 113

Django Full Text Search Not Matching Partial Words

I'm using Django Full Text search to search across multiple fields but have an issue when searching using partial strings.

Lets say we have a report object with the name 'Sample Report'.

vector = SearchVector('name') + SearchVector('author__username')

search = SearchQuery('Sa')

Report.objects.exclude(visible=False).annotate(search=vector).filter(search=search)

The following QuerySet is empty but if I include the full word 'Sample' then the report will appear in the QuerySet.

Is there anyway to use icontains or prefixing with django full text search?

Upvotes: 10

Views: 4292

Answers (2)

Tomiwa
Tomiwa

Reputation: 1054

@santiagopim solution is correct but to address Matt's comment for if you get the following error:

ERROR:  function replace(tsquery, unknown, unknown) does not exist 
at character 1603 HINT:  No function matches the given name 
and argument types. You might need to add explicit type casts.

You have to remove the call to SearchQuery and just use a plain string.

I know this doesn't address the underlying issue for if you need to use SearchQuery but if you are like me and just need a quick fix, you can try the following.


vector = SearchVector('name') + SearchVector('author__username')

# NOTE: I commented out the line below
# search = SearchQuery('Sa')
search = 'Sa'

Report.objects.exclude(visible=False).annotate(search=vector)\
.filter(search__icontains =search)

This other answer might be helpful.

Upvotes: 1

santiagopim
santiagopim

Reputation: 616

This is working on Django 1.11:

tools = Tool.objects.annotate(
    search=SearchVector('name', 'description', 'expert__user__username'),
).filter(search__icontains=form.cleaned_data['query_string'])

Note the icontains in the filter.

Upvotes: 6

Related Questions