Sub topic 17
Typo-tolerant search with pg_trgm
Full-text search matches lexemes exactly. A search for postgre does not find postgres, because the stemmer produces two different lexemes. This chapter covers the pg_trgm extension, which scores how similar two strings are and so tolerates typos. It assumes you know tsvector, tsquery, @@, and GIN indexes from earlier chapters.
What a trigram is
A trigram is a group of three consecutive characters. pg_trgm splits a string into the set of its trigrams. Two strings that share many trigrams are probably similar, even if they differ by a typo.
The extension lowercases the text and treats anything that is not a letter or digit as a word boundary. It pads each word with two spaces at the front and one at the end. show_trgm displays the result:
CREATE EXTENSION IF NOT EXISTS pg_trgm;
SELECT show_trgm('cat');
-- {" c"," ca","cat","at "}The similarity of two strings is the number of trigrams they share divided by the number of distinct trigrams in either set. It ranges from 0 (nothing in common) to 1 (identical trigram sets).
Similarity functions and operators
| Function or operator | Meaning |
|---|---|
| `similarity(a, b)` | Score from 0 to 1 over the whole strings |
| `a % b` | True if `similarity(a, b)` is at least `pg_trgm.similarity_threshold` (default 0.3) |
| `word_similarity(a, b)` | Best score of `a` against any contiguous run of words in `b` |
| `a <% b` | True if `word_similarity(a, b)` is at least `pg_trgm.word_similarity_threshold` (default 0.6) |
| `a <-> b` | Distance, equal to `1 - similarity(a, b)` |
Use similarity when both strings are about the same length, such as a person's name against a stored name. Use word_similarity when the query is short and the stored text is long, such as a few words against a product title. Plain similarity drops sharply when the lengths differ a lot.
A worked example
This example is self-contained. It creates a small table and a GIN index that uses the trigram operator class.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE tags (
id serial PRIMARY KEY,
name text NOT NULL
);
INSERT INTO tags (name) VALUES
('postgres'), ('postgresql'), ('progress'),
('python'), ('pytorch'), ('replication');
CREATE INDEX tags_name_trgm_idx ON tags USING gin (name gin_trgm_ops);
SELECT name, similarity(name, 'postgre') AS sim
FROM tags
WHERE name % 'postgre'
ORDER BY sim DESC;Both postgres and postgresql should come back, since they share most of their trigrams with postgre. Unrelated names like python fall below the threshold and are filtered out.
The % operator is what the index accelerates. Calling similarity(name, 'postgre') > 0.3 in the WHERE clause cannot use the index, because the planner has no way to map that expression to the operator class.
Tuning the threshold
The threshold is a session setting:
SET pg_trgm.similarity_threshold = 0.45;
SHOW pg_trgm.similarity_threshold;A lower value returns more candidates and more noise. A higher value is stricter and misses heavier typos. Start with the default, test against real misspellings from your users, and adjust. Short strings are the hardest case: cat has only four trigrams, so one wrong letter changes a large share of them.
Index choices
pg_trgm provides both index types, with different trade-offs:
| Row | GIN (`gin_trgm_ops`) | GiST (`gist_trgm_ops`) |
|---|---|---|
| Lookup speed | Faster for `%`, `LIKE`, `ILIKE`, regex | Slower on large tables |
| Build and update cost | Higher | Lower |
| Index size | Larger | Smaller |
| Nearest-neighbor ordering with `<->` | Not supported | Supported |
To return the five closest matches without scoring every candidate, use GiST:
CREATE INDEX tags_name_gist_idx ON tags USING gist (name gist_trgm_ops);
SELECT name, name <-> 'postgre' AS distance
FROM tags
ORDER BY name <-> 'postgre'
LIMIT 5;With a GiST index, the planner can walk the index in distance order and stop after five rows. With only a GIN index, it must find all rows over the threshold and sort them. For most typo-tolerant lookups, the % filter with GIN, followed by ORDER BY similarity(...) on the few remaining rows, is fast enough.
The GIN trigram index has a useful side effect. It also speeds up LIKE '%text%' and ILIKE patterns that a B-tree cannot help with, as long as the pattern contains at least a few characters.
Combining with full-text search
Trigrams and full-text search solve different problems, so use both. A common pattern is:
- Run the normal
@@query. - If it returns few or no rows, look up the closest known words with trigrams and offer a "did you mean" suggestion.
To build the vocabulary, use ts_stat on the articles.search column from the earlier chapters. This table is a snapshot, so rebuild it periodically.
CREATE TABLE search_words AS
SELECT word
FROM ts_stat('SELECT search FROM articles');
CREATE INDEX search_words_trgm_idx
ON search_words USING gin (word gin_trgm_ops);
SELECT word, similarity(word, 'serch') AS sim
FROM search_words
WHERE word % 'serch'
ORDER BY sim DESC
LIMIT 3;The words in this table are lexemes, so they are stemmed and may look odd, for example search or postgr. Run the suggested lexeme through your normal query path rather than showing it raw to users. If you need display-ready words, build the vocabulary from the original text instead.
Common gotchas
- The
<->operator has two meanings. In atsqueryit means "followed by" (phrase search). Withpg_trgmit is a distance between strings. The operand types decide which one is used. - Thresholds are per session. A
SETin one connection does not affect other connections. In a connection pool, set the value in the same transaction as the query, withSET LOCAL, or set it per role or database. - Non-alphanumeric characters are ignored. Strings made only of punctuation produce no trigrams and match nothing.
- Non-English text depends on locale. What counts as a letter depends on the database's locale settings. Test with your real data, especially accented characters. The
unaccentextension from the configuration chapter can normalize both sides first. - Index size. A GIN trigram index on a long text column can be larger than the table itself. Index short fields like titles, names, and a vocabulary table rather than whole bodies.
- Typos are not meaning. Trigrams find strings that look alike. They do not know that
carandautomobileare related.
Exercise
A table products(name text) has 2 million rows. Users search with misspelled product names such as samsnug. Which index and query shape would you use to return the 10 closest names, and why does WHERE similarity(name, 'samsnug') > 0.3 fail to use that index?
Show answer
Create a trigram index on the column, for example CREATE INDEX ON products USING gist (name gist_trgm_ops);, and query with ORDER BY name <-> 'samsnug' LIMIT 10. GiST supports nearest-neighbor ordering, so Postgres can stop after 10 rows. (A GIN index with WHERE name % 'samsnug' ORDER BY similarity(name, 'samsnug') DESC LIMIT 10 is also valid and faster to search, but it must sort all rows over the threshold.) The similarity(...) > 0.3 form is an ordinary function call. The planner cannot map it to the operator class, so it scans every row. The % and <-> operators are the ones the index supports.