djangopostgresqltrigram

Django trigram_similar search returns no result (Django 2.1 with Postgresql 10.5 backend)


I followed the instruction on https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/lookups/#std:fieldlookup-trigram_similar to install trigram search on my search engine. I added 'django.contrib.postgres' in my INSTALLED_APPS in settings.py and installed the pg_trgm extension on my PostgreSQL database. The trigram search returns no result, but there is no error, just blankness where there should be search results. My search engine worked fine with icontain searches. Here is the code for my search engine with trigram_similar:

def query_search(request):
    articles = cross_currents.objects.all()
    search_term = ''
    if 'keyword' in request.GET:
        search_term = request.GET['keyword']
        articles = articles.filter(Title__trigram_similar=search_term)  

Title is a CharField in my model cross_currents:

class cross_currents(models.Model):
    Title = models.CharField(max_length=500)

This is what my Django shell gave me:

In [6]: cross_currents.objects.filter(Title__trigram_similar='modern')
Out[6]: <QuerySet []>

The HTML page also returns nothing. However, when I do

cross_currents.objects.filter(Title__icontains='modern') 

many results show up. Any idea why my trigram search returns nothing?


Solution

  • The issue was that the default similarity threshold of Postgres is set to 0.3, which is way too high to return results for single word searches in my case. I find a threshold of 0.01 to be effective in my case:

    articles = articles.annotate(similarity=TrigramSimilarity('Title', search_term),).filter(similarity__gt=0.01).order_by('-similarity')