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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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 postgres user or another superuser:

1
2
$ psql website_db
website_db=# CREATE EXTENSION pg_trgm;

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