- Django 2 by Example
- Antonio Melé
- 201字
- 2021-06-25 21:19:08
Searching with trigram similarity
Another search approach is trigram similarity. A trigram is a group of three consecutive characters. You can measure the similarity of two strings by counting the number of trigrams they share. This approach turns out to be very effective for measuring the similarity of words in many languages.
In order to use trigrams in PostgreSQL, you will need to install the pg_trgm extension first. Execute the following command from the shell to connect to your database:
psql blog
Then, execute the following command to install the pg_trgm extension:
CREATE EXTENSION pg_trgm;
Let's edit our view and modify it to search for trigrams. Edit the views.py file of your blog application and add the following import:
from django.contrib.postgres.search import TrigramSimilarity
Then, replace Post search query with the following lines:
results = Post.objects.annotate(
similarity=TrigramSimilarity('title', query),
).filter(similarity__gt=0.3).order_by('-similarity')
Open http://127.0.0.1:8000/blog/search/ in your browser and test different searches for trigrams. The following example displays a hypothetical typo in the django term, showing search results for yango:
Now, you have a powerful search engine built into your project. You can find more information about full-text search at https://docs.djangoproject.com/en/2.0/ref/contrib/postgres/search/.