Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
Django Trigram Similarity query not as fast as raw query with same result

The objective is to have a fast search for similar values, in order of similarity.

This is the query in Django: Model.objects.annotate(similarity=TrigramSimilarity('field_name', query)).filter(similarity__gt=0.3).order_by('-similarity').values('field_name')[0:30]

The above is converted to this query: SELECT "table"."field_name" FROM "table" WHERE SIMILARITY("table"."field_name", query_value) > 0.3 ORDER BY SIMILARITY("table"."field_name", query_value) DESC LIMIT 30

That takes around 1.3 seconds, but if I run this in psql:

SELECT field_name FROM table WHERE field_name % 'query_value' ORDER BY similarity(field_name, 'query_value') DESC LIMIT 30

It's much faster and has the same correct output. How can I achieve this with Django, besides putting in the raw sql command?

Another question is how to add SELECT DISTINCT field_name to that. Currently when trying to add it I get ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list even though I only use the selected field_name in the ORDER BY simlarity function.

Thanks a lot!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Kinda old question but I was messing up with trigrams latgely and run into similar issue.

Very important thing is (as mentioned here - https://dba.stackexchange.com/questions/103821/best-index-for-similarity-function/103823#103823) indexes are not used when you use functions! You have to use operator - so %.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!