AI Hints
Home›PostgreSQL Tutorial›Fast Search, Fuzzy Search, Practice
PostgreSQL · Lesson 62 of 120

Fuzzy Search with pg_trgm

Typos welcome.

⏱ 2 min read▶ Video at 55:32🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Full text search doesn't fix typos. A shopper types drgons, and finds nothing. The pg trgm extension compares text by small three letter pieces, so close spellings still match.

  • 'drgons'
  • No match
  • Trigrams

Similar titles

Create extension turns on pg trgm. Similarity scores two texts from zero to one. The percent operator keeps rows that are similar enough. Run it. Dragons of Ember Bay, found from a typo.

query.sqlsql
CREATE EXTENSION pg_trgm;

SELECT title, similarity(title, 'drgons ember') AS score
FROM books
WHERE title % 'drgons ember'
ORDER BY score DESC;
Output
CREATE EXTENSION
        title         |   score
----------------------+------------
 Dragons of Ember Bay | 0.47826087
(1 row)

Trigram tricks

AGIN index with gin trgm ops makes similarity fast. It also speeds up like and i like with a percent sign at the start. And word similarity matches a word inside a longer text.

keyvalue
gin_trgm_opsfast fuzzy
ILIKE '%x%'now indexable
word_similarityword in text
Thresholdpg_trgm.similarity_threshold

Summary

Pg trgm finds similar text using trigrams, so typos still match. Next, practise with a book search.

Key takeaways
  • pg_trgm
  • similarity
  • %
Next up: Practice: Book Search — words and typos