About Fuzzy Full-text Search

When you need approximate full-text search results for searches with spelling mistakes in the query, with different word endings, or without diacritical symbols, you can use Trigram search in PostgreSQL.

Here's how it could look in a Django queryset:

from django.db import models
from django.db.models.functions import Concat
from django.contrib.postgres.search import TrigramWordSimilarity
from posts.models import Post

search_string = "Django"

posts_about_django = Post.objects.annotate(
    combined_search_data=Concat(
        "title",
        models.Value("|"),
        "description",
        output_field=models.TextField(),
    ),
    similarity=TrigramWordSimilarity(
        expression="combined_search_data",
        string=search_string,
    ),
).filter(similarity__gt=0.5)

For this, you will need to install pg_trgm extension to your PostgreSQL database as a superuser:

$ psql --username=postgres --dbname=website_db
website_db=# CREATE EXTENSION pg_trgm;

Tips and Tricks Programming Development Databases Django 5.2 Django 4.2 Django 3.2 PostgreSQL

Django/Python Consulting

If you have a specific Django challenge or integration you'd like to solve, I'd be happy to help. Book a free 30-minute call to discuss your project, see if we're a good fit, and explore the best approach for your needs. After the call, you'll receive a tailored cost estimate based on what we discuss.