full-text and fuzzy search
tsvector, tsquery, ranking, pg_trgm for LIKE '%foo%', and the GIN index behind both.
- address
- everything.indexes.text_search
- part
- part 8, indexes, from the outside
- chapter
- chapter 12 of 12
- reading time
- 8 min
LIKE '%whisk%' scans every row and only matches letters. full-text search turns text into a tsvector of normalized words (lexemes: "wobbles" becomes wobbl, "the" disappears), turns the search into a tsquery, and matches them with @@. ts_rank orders the hits. a GIN index holds one entry per lexeme with the list of rows that contain it, so a search reads a few lists instead of every row.
for "contains these letters" and typo tolerance, the pg_trgm extension indexes three-letter fragments instead.
the picture
you know the index at the back of a textbook? it's the original full-text index. every important word, normalized ("pour" and "pouring" under one entry, "the" not at all), with the pages it appears on. to find pages about pouring teapots, you look up two entries and see which pages are in both.
postgres builds exactly that. first, a sentence becomes lexemes:
| aliastext | tokentext | lexemes_text |
|---|---|---|
| asciiword | The | {} |
| asciihword | left-handed | {left-hand} |
| hword_asciipart | left | {left} |
| hword_asciipart | handed | {hand} |
| asciiword | teapots | {teapot} |
| asciiword | pour | {pour} |
| asciiword | the | {} |
| asciiword | other | {} |
| asciiword | way | {way} |
english configuration takes a sentence apart: each token, and the lexeme it became. "The", "the" and "other" are stop words and vanish. "teapots" is stemmed to teapot, "handed" to hand, and the hyphenated word is kept whole and in parts.then each lexeme points at the rows that contain it. here are a few words from shop's product names, and which products have them:
a search for whisk & steel reads two lists and intersects them. that's why GIN is the index for "contains" questions (index types), and why its insides are called an inverted index (GIN).
tsvector and tsquery
SELECT to_tsvector('english', 'The left-handed teapot pours the other way.') AS doc;
SELECT to_tsquery('english', 'teapots & pouring') AS query;
SELECT to_tsvector('english', 'The left-handed teapot pours the other way.')
@@ to_tsquery('english', 'teapots & pouring') AS matches;| doctsvector |
|---|
| 'hand':4 'left':3 'left-hand':2 'pour':6 'teapot':5 'way':9 |
| querytsquery |
|---|
| 'teapot' & 'pour' |
| matchesbool |
|---|
| t |
the numbers in the tsvector are word positions, which ranking and phrase search use. the query was normalized with the same rules, so "teapots" and "pouring" meet "teapot" and "pour" in the middle. that's the whole point of lexemes, and also why the configuration (english) has to be the same on both sides.
for text a user typed, websearch_to_tsquery takes the syntax people expect from a search box (quotes for phrases, - to exclude, or):
SELECT websearch_to_tsquery('english', '"left handed" teapot -cup') AS query;| querytsquery |
|---|
| 'left' <-> 'hand' & 'teapot' & !'cup' |
an index for it
the usual setup is a generated column with the tsvector, kept in sync by postgres, and a GIN index on it. here are 20,000 product reviews, generated from shop's product names:
CREATE TABLE reviews (id int PRIMARY KEY, product_id int NOT NULL, body text NOT NULL);
INSERT INTO reviews
SELECT i, p.id,
'the ' || p.name || ' ' || (ARRAY['arrived quickly and works well', 'broke after a week', 'is smaller than it looks',
'is great value for the price', 'has a handle that wobbles', 'pours the wrong way', 'stopped working after a month',
'is exactly as described', 'is too heavy to carry', 'makes a terrible noise', 'was a gift and they loved it',
'feels cheap but does the job'])[1 + ((hashint4(i)::bigint + 2147483648) % 12)::int]
FROM generate_series(1, 20000) AS i
JOIN products AS p ON p.id = 1 + (i * 37) % 199
ORDER BY i;
ALTER TABLE reviews ADD COLUMN doc tsvector GENERATED ALWAYS AS (to_tsvector('english', body)) STORED;
CREATE INDEX reviews_doc ON reviews USING gin (doc);
VACUUM ANALYZE reviews;
SELECT id, body FROM reviews ORDER BY id LIMIT 3;| idint4 | bodytext |
|---|---|
| 1 | the spare trowel stopped working after a month |
| 2 | the heavy lantern stopped working after a month |
| 3 | the smart speaker is exactly as described |
(hashint4 of the row number picks the phrase, so every engine builds the same rows.) now the search:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, body FROM reviews WHERE doc @@ to_tsquery('english', 'whisk & wobble');whisk reviews that mention a wobble: the GIN index looks up both lexemes, intersects their lists, and only those rows are fetched.
doc, and on a tsvector computed on the fly with another configuration, which no index covers. the index reads 5 index pages and then only the heap pages with a match: 42 pages against 387.SELECT count(*) FROM reviews WHERE doc @@ to_tsquery('english', 'wobbles');SELECT count(*) AS english FROM reviews WHERE doc @@ to_tsquery('english', 'wobbles');
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT count(*) FROM reviews WHERE doc @@ to_tsquery('simple', 'wobbles');| englishint8 |
|---|
| 1605 |
ranking
@@ is yes or no. to put the best matches first, ts_rank scores each match by how many query words it has and how often; ts_rank_cd also rewards them for being close together. here's the spread for whisk | wobble:
| ranknumeric | reviewsint8 | exampletext |
|---|---|---|
| 0.0608 | 38 | the compact whisk has a handle that wobbles |
| 0.0304 | 2032 | the bamboo binder has a handle that wobbles |
whisk | wobble, grouped by their ts_rank. the ones with both words score twice as high as the ones with one.SELECT id, body, round(ts_rank(doc, q)::numeric, 4) AS rank
FROM reviews, to_tsquery('english', 'whisk | wobble') AS q
WHERE doc @@ q
ORDER BY rank DESC, id
LIMIT 3;| idint4 | bodytext | ranknumeric |
|---|---|---|
| 165 | the heavy whisk has a handle that wobbles | 0.0608 |
| 394 | the compact whisk has a handle that wobbles | 0.0608 |
| 792 | the compact whisk has a handle that wobbles | 0.0608 |
ranking has to compute a score for every match, and the index doesn't help with that part: a search that matches half the table and then sorts by rank is slow however it's indexed. narrow first, rank second. and note the id after rank DESC: equal ranks are common, and without a tiebreaker the order among them isn't defined.
fuzzy: pg_trgm
full-text search matches words. it won't find whis inside whisk, or wisk for whisk. for that, the pg_trgm extension breaks text into trigrams (every run of three characters, with padding at word edges) and compares the sets. these blocks load it first, the way CREATE EXTENSION pg_trgm; would on a server:
SELECT show_trgm('whisk') AS trigrams;
SELECT id, name, round(similarity(name, 'larje wisk')::numeric, 3) AS similarity
FROM products
WHERE name % 'larje wisk'
ORDER BY similarity DESC, id;| trigramstext[] |
|---|
| {" w"," wh",his,isk,"sk ",whi} |
| idint4 | nametext | similaritynumeric |
|---|---|---|
| 9 | large whisk | 0.353 |
| 19 | large whisk | 0.353 |
two misspellings, and both large whisks still come back. % is "similar enough" (similarity above pg_trgm.similarity_threshold, 0.3 by default). a GIN index with the gin_trgm_ops operator class serves it, and it also serves LIKE and ILIKE with a wildcard at the start, which no b-tree can:
CREATE INDEX products_name_trgm ON products USING gin (name gin_trgm_ops);
SET enable_seqscan = off;
EXPLAIN (COSTS OFF) SELECT name FROM products WHERE name LIKE '%whisk%';
EXPLAIN (COSTS OFF) SELECT name FROM products WHERE name ILIKE '%WHISK%';(products has 200 rows, so the seq scan is switched off to show that the index can serve the query; on a real table postgres picks it by itself.) trigram indexes are big, a few entries per word of every row, and they need at least three characters of pattern to narrow anything.
keylines
- tsvector: text as normalized lexemes. tsquery: the search, normalized the same way.
- @@ matches, ts_rank orders. same configuration on both sides.
- a GIN index stores each lexeme with the rows that contain it.
- pg_trgm: trigrams for LIKE '%foo%', ILIKE and typo tolerance, also with GIN.