Django - Full text search - Wildcard

Viewed 3232

Is it possible to use wildcards in Django Full text search ?

https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/search/

post = request.POST.get('search')
query = SearchQuery(post)
vector = SearchVector('headline', weight='A') + SearchVector('content', weight='B')
rank = SearchRank(vector, query, weights=[0.1,0.2])
data = wiki_entry.objects.annotate(rank=SearchRank(vector,query)).filter(rank__gte=0.1).order_by('-rank')

At the moment it only matches on full words.

Characters like * % | & have no effect.

Or do i have to go back to icontains ?

https://docs.djangoproject.com/en/1.11/ref/models/querysets/#icontains

Any help is appreciated

2 Answers

I extend the django SearchQuery class and override plainto_tsquery with to_tsquery. Did some simple tests, it works. I will get back here if I find cases where this causes problems.

from django.contrib.postgres.search import SearchQuery

class MySearchQuery(SearchQuery):
    def as_sql(self, compiler, connection):
        params = [self.value]
        if self.config:
            config_sql, config_params = compiler.compile(self.config)
            template = 'to_tsquery({}::regconfig, %s)'.format(config_sql)
            params = config_params + [self.value]
        else:
            template = 'to_tsquery(%s)'
        if self.invert:
            template = '!!({})'.format(template)
        return template, params

Now I can do something like query = MySearchQuery('whatever:*')

Related