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
Also by me
Django Messaging 🎅🏼
For Django-based social platforms.
Django Paddle Subscriptions 🎅🏼
For Django-based SaaS projects.
Django GDPR Cookie Consent 🎅🏼
For Django websites that use cookies.