Topic 2 of 5 · 4 min read
Full-text search built into PostgreSQL
Goal: Add ranked full-text search to a table with a generated tsvector column and an index, and name one kind of query it misses.
Store a normalised, searchable version of your text in a generated tsvector column, index it with GIN, and query it with a tsquery. For many apps this is all the search they need, and it lives in the database you already back up.
Check yourself · 1 of 3
Why does a full-text search for 'invoices' also find a row containing 'invoice'?
Why it matters
WHERE body ILIKE '%invoice%' scans every row and matches letters, not words. It misses "invoices", ranks nothing and slows as the table grows. Full-text search turns text into lexemes (stemmed words, with common words such as "the" removed) so "invoices" and "invoice" match, and it can rank results.
How to do it
- Pick a configuration.
to_tsvector('english', text)applies English stemming and stop words. Use the language of the content. Mixed-language text needs a per-row language column or a simpler configuration. - Add a generated column. The column is computed on write, so you never forget to update it.
- Index it. A GIN index on the tsvector column makes
@@matches fast. - Build the query.
websearch_to_tsqueryaccepts what users type, including quotes and a minus sign, and does not raise errors on odd input.to_tsqueryis strict and fails on malformed text. - Rank.
ts_rankorts_rank_cdscores matches. Weights (A to D viasetweight) make a title match count more than a body match. - Know the edge. Search the query plan before you promise anything: the index finds matches, ranking still reads every matching row.
Before and after
-- Weak: scans, no stemming, no ranking
SELECT id, title FROM articles WHERE body ILIKE '%refund policy%';
ALTER TABLE articles ADD COLUMN search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title,'')), 'A') ||
setweight(to_tsvector('english', coalesce(body,'')), 'B')
) STORED;
CREATE INDEX articles_search_idx ON articles USING GIN (search);
SELECT id, title, ts_rank(search, q) AS score
FROM articles, websearch_to_tsquery('english', 'refund policy') q
WHERE search @@ q
ORDER BY score DESC LIMIT 20;
What goes wrong
- Typos. Full-text search matches stems, not misspellings. "refnd" finds nothing. The pg_trgm extension handles fuzzy matching.
- Wrong language configuration. Indexing with 'english' and querying with 'simple' gives mismatched lexemes and silent misses.
- No meaning match. "money back" will not find "refund". That is where embeddings, or a search engine with synonym support, come in.
- Expecting engine features. Faceted counts, highlight snippets at scale and per-field tuning get awkward. When you need them, move to a dedicated search engine.
Examples
Typo-tolerant fallback with trigrams
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX products_name_trgm ON products USING GIN (name gin_trgm_ops);
SELECT name FROM products
WHERE name % 'blutooth speaker'
ORDER BY similarity(name, 'blutooth speaker') DESC LIMIT 5;
Use this when the full-text query returns nothing. It matches on character overlap, so the misspelling still finds "Bluetooth speaker".
Why a query returns no rows
-- search built with 'english', query uses 'simple'
SELECT id FROM articles
WHERE search @@ websearch_to_tsquery('simple', 'running');
The english column stores the lexeme run. The simple configuration looks for running. Use the same configuration on both sides.
Key points
- A generated tsvector column plus a GIN index gives indexed, ranked word search with no application code to keep it current.
- Use the same configuration to build the tsvector and the query, or the lexemes will not line up.
- websearch_to_tsquery is the safe choice for user-typed input; to_tsquery raises errors on malformed text.
- setweight lets a title match outrank a body match when ranking.
- Full-text search matches stems of words, so it misses typos and synonyms; pg_trgm helps with typos and embeddings with meaning.
- Postgres search is enough for one language, modest size and simple ranking; faceting and heavy tuning point to a search engine.
Common mistakes
- Using ILIKE '%term%' on a large table and calling it search.
- Building the tsvector with one language configuration and the query with another.
- Passing raw user input to to_tsquery and letting stray punctuation raise syntax errors.
- Expecting full-text search to find synonyms or misspellings.
Check yourself · 2 of 3
Which setup keeps a search column current without any application code?
Check yourself · 3 of 3
A user searches 'money back' but your help article says 'refund'. Plain Postgres full-text search returns nothing. What does this show?
Practice items, not counted towards your mastery.
Start here
- PostgreSQL: JSON types (opens in a new tab)DocsFree
jsonb versus json, the containment operator and the GIN operator classes.
- PostgreSQL: Full text search (opens in a new tab)DocsFree
tsvector, tsquery, ranking, configurations and indexes for text search.
- pgvector: open-source vector similarity search for Postgres (opens in a new tab)ToolFree
Vector types, HNSW and IVFFlat settings, filtering and the trade-offs of each index.