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 ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.