skip to content

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:

aliastexttokentextlexemes_text
asciiwordThe{}
asciihwordleft-handed{left-hand}
hword_asciipartleft{left}
hword_asciiparthanded{hand}
asciiwordteapots{teapot}
asciiwordpour{pour}
asciiwordthe{}
asciiwordother{}
asciiwordway{way}
(9 rows)
real output, postgres 18.6 (PGlite 0.5.12) · text-search
how the 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:

an inverted index, built with a real query over product names: each lexeme and the ids of the products whose name contains it. a GIN index stores the same thing, as a b-tree of lexemes with a list of row addresses under each.

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

sqlempty db
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;
output, from postgres 18.6
#1 · SELECT 1
doctsvector
'hand':4 'left':3 'left-hand':2 'pour':6 'teapot':5 'way':9
(1 row)
#2 · SELECT 1
querytsquery
'teapot' & 'pour'
(1 row)
#3 · SELECT 1
matchesbool
t
(1 row)

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):

sqlempty db
SELECT websearch_to_tsquery('english', '"left handed" teapot -cup') AS query;
output, from postgres 18.6
SELECT 1
querytsquery
'left' <-> 'hand' & 'teapot' & !'cup'
(1 row)

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:

sqldb=shop · session fts
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;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 20000
#3 · ALTER TABLE
#4 · CREATE INDEX
#5 · VACUUM
#6 · SELECT 3
idint4bodytext
1the spare trowel stopped working after a month
2the heavy lantern stopped working after a month
3the smart speaker is exactly as described
(3 rows)

(hashint4 of the row number picks the phrase, so every engine builds the same rows.) now the search:

sqldb=shop · session fts
continues session fts (1 earlier block run first)
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT id, body FROM reviews WHERE doc @@ to_tsquery('english', 'whisk & wobble');
output, from postgres 18.6
EXPLAIN
Bitmap Heap Scan on reviews (actual rows=38.00 loops=1) Recheck Cond: (doc @@ '''whisk'' & ''wobbl'''::tsquery) Heap Blocks: exact=37 Buffers: shared hit=42 -> Bitmap Index Scan on reviews_doc (actual rows=38.00 loops=1) Index Cond: (doc @@ '''whisk'' & ''wobbl'''::tsquery) Index Searches: 1 Buffers: shared hit=5 Planning: Buffers: shared hit=9 read=1
tsvector =
SELECT id, body FROM reviews WHERE doc @@ to_tsquery('english', 'whisk & wobble')
pages read by the whole query (Buffers: shared hit + read)
42 pages
387 pages

whisk reviews that mention a wobble: the GIN index looks up both lexemes, intersects their lists, and only those rows are fetched.

real output, postgres 18.6 (PGlite 0.5.12) · text-search
the same search through the GIN index on 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.
predict the output
the index is on doc, built with 'english'. which WHERE can use it?
sql
SELECT count(*) FROM reviews WHERE doc @@ to_tsquery('english', 'wobbles');
sqldb=shop · session fts
continues session fts (2 earlier blocks run first)
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');
output, from postgres 18.6
#1 · SELECT 1
englishint8
1605
(1 row)
#2 · EXPLAIN
Aggregate (actual rows=1.00 loops=1) Buffers: shared hit=3 -> Bitmap Heap Scan on reviews (actual rows=0.00 loops=1) Recheck Cond: (doc @@ '''wobbles'''::tsquery) Buffers: shared hit=3 -> Bitmap Index Scan on reviews_doc (actual rows=0.00 loops=1) Index Cond: (doc @@ '''wobbles'''::tsquery) Index Searches: 1 Buffers: shared hit=3 Planning: Buffers: shared hit=10

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:

ranknumericreviewsint8exampletext
0.060838the compact whisk has a handle that wobbles
0.03042032the bamboo binder has a handle that wobbles
(2 rows)
real output, postgres 18.6 (PGlite 0.5.12) · text-search
reviews matching whisk | wobble, grouped by their ts_rank. the ones with both words score twice as high as the ones with one.
sqldb=shop · session fts
continues session fts (3 earlier blocks run first)
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;
output, from postgres 18.6
SELECT 3
idint4bodytextranknumeric
165the heavy whisk has a handle that wobbles0.0608
394the compact whisk has a handle that wobbles0.0608
792the compact whisk has a handle that wobbles0.0608
(3 rows)

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:

sqldb=shop · ext=pg_trgm
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;
output, from postgres 18.6
#1 · SELECT 1
trigramstext[]
{" w"," wh",his,isk,"sk ",whi}
(1 row)
#2 · SELECT 2
idint4nametextsimilaritynumeric
9large whisk0.353
19large whisk0.353
(2 rows)

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:

sqldb=shop · ext=pg_trgm
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%';
output, from postgres 18.6
#1 · CREATE INDEX
#2 · SET
#3 · EXPLAIN
Bitmap Heap Scan on products Recheck Cond: (name ~~ '%whisk%'::text) -> Bitmap Index Scan on products_name_trgm Index Cond: (name ~~ '%whisk%'::text)
#4 · EXPLAIN
Bitmap Heap Scan on products Recheck Cond: (name ~~* '%WHISK%'::text) -> Bitmap Index Scan on products_name_trgm Index Cond: (name ~~* '%WHISK%'::text)

(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.