Full answer
Tables and rows used here:
CREATE TABLE articles (
id int PRIMARY KEY,
title text,
body text,
search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'B')) STORED
);
CREATE INDEX articles_search ON articles USING gin (search);
INSERT INTO articles (id, title, body) VALUES
(1, 'Indexing strategies', 'How B-tree and GIN indexes speed up queries.'),
(2, 'Query tuning basics', 'Reading plans and choosing indexes for slow queries.'),
(3, 'Backups', 'Point in time recovery keeps data safe.');SELECT id, title, round(ts_rank(search, q)::numeric, 3) AS rank FROM articles, websearch_to_tsquery('english', 'index queries') q WHERE search @@ q ORDER BY rank DESC, id;PostgreSQL returns:
id | title | rank
----+---------------------+-------
2 | Query tuning basics | 0.683
1 | Indexing strategies | 0.504
(2 rows)SELECT websearch_to_tsquery('english', '"point in time" -backups or tuning')::text AS parsed;Result on PostgreSQL 17:
parsed
-----------------------------------------
'point' <2> 'time' & !'backup' | 'tune'
(1 row)SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT id FROM articles WHERE search @@ websearch_to_tsquery('english', 'recovery');Result:
Bitmap Heap Scan on articles
Recheck Cond: (search @@ '''recoveri'''::tsquery)
-> Bitmap Index Scan on articles_search
Index Cond: (search @@ '''recoveri'''::tsquery)Both indexing articles match 'index queries' after stemming (indexes and indexing reduce to index, queries to queri), and article 3 does not. Each matching article has one search word in its A-weighted title and both words in its body, and ts_rank's weighting and frequency scoring puts article 2 slightly ahead. The parsed query shows how websearch syntax becomes tsquery operators: the quoted phrase becomes a sequence with <2> rather than <->, because the dropped stop word 'in' still occupies a position, the minus sign becomes NOT and 'or' becomes |, and stop words such as 'in' are dropped. The GIN index serves the match, shown here with sequential scans disabled because the table is tiny. The generated column means application code never has to remember to update the vector.
CREATE TABLE articles (
id int PRIMARY KEY,
title text,
body text,
search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'B')) STORED
);
CREATE INDEX articles_search ON articles USING gin (search);
INSERT INTO articles (id, title, body) VALUES
(1, 'Indexing strategies', 'How B-tree and GIN indexes speed up queries.'),
(2, 'Query tuning basics', 'Reading plans and choosing indexes for slow queries.'),
(3, 'Backups', 'Point in time recovery keeps data safe.');
SELECT id, title, round(ts_rank(search, q)::numeric, 3) AS rank FROM articles, websearch_to_tsquery('english', 'index queries') q WHERE search @@ q ORDER BY rank DESC, id;
SELECT websearch_to_tsquery('english', '"point in time" -backups or tuning')::text AS parsed;
SET enable_seqscan = off; EXPLAIN (COSTS OFF) SELECT id FROM articles WHERE search @@ websearch_to_tsquery('english', 'recovery');Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- Generated tsvector columns stay in sync
- setweight ranks title above body
- websearch_to_tsquery parses user input safely
- ts_rank orders results
- GIN indexes serve @@
Common mistakes
- Building tsquery strings from raw user input
- Recomputing to_tsvector in every query
Follow-ups
- How would you support multiple languages?
- When is a search engine such as OpenSearch worth adding?
Tips
- Explain the weights