Sub topic 17
Typo-Tolerant Search with `pg_trgm`
This chapter assumes that you know basic SELECT, WHERE, and ORDER BY queries, and that you can create PostgreSQL extensions and indexes. It also assumes that you have seen PostgreSQL full-text search with tsvector, tsquery, and @@.
Full-text search is good at language-aware matching. It handles stemming, stop words, and word order. It is not designed to find a misspelled product name such as postgre when the stored value is postgres. The pg_trgm extension adds similarity search based on trigrams.
A trigram is a group of three consecutive characters. PostgreSQL compares the trigrams in two strings and returns a similarity score from 0 to 1.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE products (
id bigserial PRIMARY KEY,
name text NOT NULL
);
INSERT INTO products (name) VALUES
('PostgreSQL'),
('PostGIS'),
('MySQL'),
('SQLite');
CREATE INDEX products_name_trgm_idx
ON products USING gin (name gin_trgm_ops);The gin_trgm_ops operator class tells the GIN index how to index trigrams. Without it, a normal text index cannot support trigram operators.
Similarity operators and ranking
The % operator returns true when two strings are similar enough. The threshold is controlled by pg_trgm.similarity_threshold, which is usually 0.3.
SELECT name,
similarity(name, 'postgre') AS score
FROM products
WHERE name % 'postgre'
ORDER BY score DESC;The filter finds candidate rows. The ORDER BY clause ranks them so that the closest spelling appears first.
| Feature | Example | Use |
|---|---|---|
| Similarity score | `similarity(name, 'postgre')` | Measure overall similarity |
| Similarity operator | `name % 'postgre'` | Filter similar values |
| Word similarity | `word_similarity('postgre', name)` | Compare a search string with parts of longer text |
For a longer field, word_similarity can find a similar word inside a sentence. Its related <% operator performs the matching test.
SELECT name,
word_similarity('postgre', name) AS score
FROM products
WHERE 'postgre' <% name
ORDER BY score DESC;Choosing an index
GIN indexes usually work well for read-heavy searches over text columns. GiST indexes can also support pg_trgm and may be preferable when the column changes often or when you need GiST-specific behavior.
CREATE INDEX products_name_gist_trgm_idx
ON products USING gist (name gist_trgm_ops);Do not create both indexes without measuring. Each index consumes storage and makes writes slower. Use EXPLAIN to check whether PostgreSQL uses the intended index.
Combining full-text and fuzzy search
Use full-text search when users search for concepts or several words. Use pg_trgm for names, identifiers, autocomplete, and spelling mistakes. An application can run both searches and combine their results, or use trigram matching to find a likely corrected term before running full-text search.
Exercise
Which condition finds product names similar to the input and lets the query rank the closest result first?
Show answer
Use WHERE name % 'postgre' and ORDER BY similarity(name, 'postgre') DESC.