skip to content

With PostgreSQL's pg_trgm extension, how do similarity() and the % operator match misspelled search terms, and what sets the cut-off?

level: middleimportance: must knowfreq 52%

answer

  1. three-character slices
  2. two spaces before, one after
  3. shared over union
  4. a session-settable threshold
  5. word_similarity for long titles

basics

~10 s

pg_trgm splits strings into lower-cased three-character trigrams and similarity() returns shared trigrams divided by all distinct trigrams, from 0 to 1. The % operator is true when that score reaches pg_trgm.similarity_threshold, default 0.3.

solid answer

~40 s

`pg_trgm` ignores non-alphanumeric characters, lower-cases the text and pads each word with two leading spaces and one trailing space, so `cat` yields `' c'`, `' ca'`, `'cat'` and `'at '`. `similarity(a, b)` divides the trigrams the two strings share by the distinct trigrams in either: `similarity('pasword', 'password')` is 7 / 10 = 0.7. `a % b` is true when that score reaches `pg_trgm.similarity_threshold`, default `0.3`, which you change with `SET` per session or `ALTER DATABASE ... SET`. Comparing a short term with a long title dilutes the score, so `word_similarity()` with `<%` (threshold `pg_trgm.word_similarity_threshold`, default `0.6`) scores the best-matching stretch of the title instead. `<->` returns `1 - similarity` for nearest-first ordering. Trigrams complement full-text search: they tolerate typos but know nothing of stems or stop words.

code

sql · 12 lines
sql
CREATE EXTENSION IF NOT EXISTS pg_trgm;

SELECT similarity('pasword', 'password');   -- 0.7  (7 shared / 10 distinct)
SELECT similarity('paswrod', 'password');   -- about 0.21, below 0.3
SELECT 'pasword' % 'password';              -- true at the default 0.3

SET pg_trgm.word_similarity_threshold = 0.5;
SELECT id, title, word_similarity('pasword', title) AS score
FROM help_article
WHERE 'pasword' <% title
ORDER BY score DESC
LIMIT 10;

go deeper

for a junior

Know that pg_trgm gives typo-tolerant matching by comparing three-letter slices, that similarity() returns 0 to 1, and that % means similar enough.

for a middle

Explain the padding, the shared-over-union formula, the 0.3 default of pg_trgm.similarity_threshold and why word_similarity with <% suits short terms against longer titles.

for a senior

Tune the threshold per workload, use distance ordering for top-N suggestions, and combine trigrams with full-text search through a ts_stat word list rather than replacing one with the other.

for a principal

Decide where fuzziness lives: database trigrams are cheap and transactional, while typo tolerance across languages and huge corpora may justify a dedicated search service.

## The problem trigrams solve Full-text search in PostgreSQL matches **lexemes**: whole words after stemming. A help-centre user who types `pasword` gets nothing, because no article contains that lexeme. The contrib extension **`pg_trgm`** adds character-level fuzzy matching that tolerates such typos. It measures how many short character sequences two strings share. ## How a string becomes trigrams A **trigram** is a group of three consecutive characters. `pg_trgm` builds the set for a string like this: 1. Non-word characters (anything that is not alphanumeric) are treated as word separators. 2. The text is lower-cased, so `Password` and `password` give the same trigrams. 3. Each word is padded with **two spaces in front and one behind**. 4. Every three-character window is collected, and duplicates are removed. `cat` therefore yields `' c'`, `' ca'`, `'cat'` and `'at '`; `show_trgm('cat')` returns that set as an array, which is mainly a debugging aid. The padding gives the start of a word extra weight, which is why a typo near the beginning hurts more than one near the end. ## similarity(), %, and the threshold `similarity(a, b)` returns **shared trigrams divided by the number of distinct trigrams across both strings** (the size of the union), from `0` (nothing in common) to `1` (identical sets): - `password` has 9 trigrams and `pasword` has 8; they share 7, so the union is 9 + 8 - 7 = 10 and `similarity('pasword', 'password')` is **0.7**; - the transposition `paswrod` shares only 3 trigrams with `password` (`' p'`, `' pa'`, `'pas'`), so its score is 3 / 14, about 0.21. The boolean operator `a % b` returns true when the similarity reaches **`pg_trgm.similarity_threshold`**. Its default is **`0.3`**, so `pasword` matches and `paswrod` does not. The parameter is user-settable: `SET pg_trgm.similarity_threshold = 0.4` for one session, or `ALTER DATABASE ... SET` / `ALTER ROLE ... SET` for a default. The older `set_limit()` and `show_limit()` functions still exist but are deprecated in favour of the parameter. ## Short terms against long text: word similarity Plain `similarity()` compares whole strings. Matching the term `pasword` against the title *How to reset your password* scores low, because the title contributes many trigrams the term lacks and they all count in the union. `pg_trgm` has two functions for this case: | Function | Operator | Threshold parameter (default) | Scores | |---|---|---|---| | `similarity(a, b)` | `a % b` | `pg_trgm.similarity_threshold` (0.3) | whole string against whole string | | `word_similarity(a, b)` | `a <% b` | `pg_trgm.word_similarity_threshold` (0.6) | `a` against the best continuous stretch of `b` | | `strict_word_similarity(a, b)` | `a <<% b` | `pg_trgm.strict_word_similarity_threshold` (0.5) | `a` against the best run of whole words in `b` | For typo-tolerant title search, `'pasword' <% title` ordered by `word_similarity('pasword', title)` is the usual shape. Two practical cautions about thresholds: - **Short terms are volatile.** A three-letter word has only four trigrams, so one wrong letter in the middle can leave a single shared trigram and a score near 0.14; many applications skip fuzzy lookup until the user has typed four or five characters. - **Length matters for suggestions.** The manual suggests also requiring that a suggested word have a length similar to the misspelled one, which removes long words that merely share a prefix. ## Ranking by distance The distance operators return one minus the corresponding similarity: `a <-> b` for `similarity`, `a <<-> b` for `word_similarity` and `a <<<-> b` for `strict_word_similarity`. `ORDER BY title <-> 'pasword' LIMIT 10` returns the ten closest titles without choosing a threshold. Whether an index can serve that ordering, and the `gin_trgm_ops` / `gist_trgm_ops` operator classes that also accelerate `LIKE '%x%'`, `ILIKE` and regular expressions, belong to PostgreSQL's GIN and GiST index material. ## Trigrams and full-text search together The two mechanisms fail in opposite places: - **Full-text search** knows that `resetting` and `reset` are the same word, drops stop words and ranks by lexeme positions, but has no notion of a typo. - **Trigrams** forgive typos and partial words, but treat `passwords` and `password` merely as similar strings and know nothing of language. The PostgreSQL manual's own pattern combines them for a *did you mean* feature: collect the distinct words of the corpus with `ts_stat('SELECT to_tsvector(''simple'', body) FROM help_article')` into a `words` table, then look up a misspelled term with `%` or `<->` against that table and rerun the full-text query with the corrected word. The `simple` configuration keeps the words unstemmed, so the suggestions are real words. The table has to be regenerated periodically, but it does not need to be exactly current.

  • Why does 'pasword' match 'password' under the default threshold while 'paswrod' does not?
    A dropped letter leaves most trigrams intact: 7 of the 10 distinct trigrams are shared, so the score is 0.7. The transposition rewrites every trigram after `pas`, leaving 3 shared out of 14, about 0.21, which is under `pg_trgm.similarity_threshold`'s default of 0.3.
  • How do pg_trgm and full-text search combine into a 'did you mean' suggestion?
    Build a table of the corpus's distinct unstemmed words with `ts_stat` over `to_tsvector('simple', body)`, look up the user's misspelled word against it with `%` or `<->`, and rerun the full-text query with the best match. Regenerate the word table periodically; it does not need to be exactly current.
  • How do you return the ten closest titles without choosing a similarity threshold?
    Order by distance: `ORDER BY title <-> 'pasword' LIMIT 10`, where `<->` is one minus `similarity()`; `<<->` does the same for `word_similarity()`. Whether an index can return rows in that order depends on the trigram operator class, which is indexing material.

  • pg_trgm is case-sensitive, so 'Password' and 'password' score differently.
  • The % operator uses a fixed cut-off of 0.5 that cannot be changed.
  • similarity() compares a short term with a long title fairly.
  • pg_trgm stems words, so 'passwords' and 'password' score exactly 1.
  • set_limit() is the preferred way to change the % threshold today.