PostgreSQL’s full-text search is good enough that a lot of applications skip a separate search service entirely. The pieces are tsvector (a normalised, ranked vector of lexemes), tsquery (a parsed query expression), the @@ operator that matches them, GIN as the index, and configurable language dictionaries that handle stemming and stop-words. This article covers the build that holds in production — generated columns, ranking, multilingual content, and what to watch when the table grows.
How to verify
Confirm dictionaries are available and the column is indexed:
psql -d app -c "SELECT * FROM pg_ts_config;"
psql -d app -c "\d documents"
psql -d app -c "SELECT to_tsvector('english', 'PostgreSQL is a database');"
psql -d app -c "EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM documents
WHERE search_vector @@ to_tsquery('english','postgres & database')
ORDER BY ts_rank(search_vector, to_tsquery('english','postgres & database')) DESC
LIMIT 10;"
The EXPLAIN should show Bitmap Index Scan using ... gin. If it shows a sequential scan, the index isn’t being used.
What’s happening
to_tsvector('english', 'PostgreSQL is a database') produces something like 'databas':4 'postgresql':1. The english configuration applies the English stemmer (Snowball), removes stop-words (“is”, “a”), and lowercases. Each lexeme gets a position used for phrase queries and proximity ranking. to_tsquery('english', 'postgres & database') parses the query the same way: stem, strip stops, build a boolean expression with &, |, !, and <-> (proximity).
The @@ operator returns true if every required lexeme in the query appears in the vector. GIN indexes the vector — one posting list per lexeme, lookup is O(lexemes-in-query). ts_rank and ts_rank_cd score how well a vector matches; the cover-density variant gives more weight to clusters of matching terms.
The choice of configuration is the most consequential decision. english doesn’t handle French; french doesn’t handle quoted technical terms. For mixed content, you either pick a “simple” configuration (no stemming, exact match only) or maintain multiple vectors.
The procedure
-
Add a generated tsvector column on PG 12+:
ALTER TABLE documents ADD COLUMN search_vector tsvector GENERATED ALWAYS AS ( setweight(to_tsvector('english', coalesce(title, '')), 'A') || setweight(to_tsvector('english', coalesce(subtitle, '')), 'B') || setweight(to_tsvector('english', coalesce(body, '')), 'C') ) STORED; CREATE INDEX documents_search_gin ON documents USING GIN (search_vector);setweightassigns A/B/C/D sots_rank_cdcan weight title matches above body matches. The column isSTORED— it occupies disk but is computed automatically on INSERT and UPDATE. -
Query with ranking:
SELECT id, title, ts_rank_cd(search_vector, query) AS rank, ts_headline('english', body, query) AS snippet FROM documents, to_tsquery('english', 'postgres <-> tuning | performance') query WHERE search_vector @@ query ORDER BY rank DESC LIMIT 20;ts_headlinereturns the body with<b>tags around matched terms — useful for the search-results snippet. -
Use
websearch_to_tsqueryfor user input:SELECT id FROM documents WHERE search_vector @@ websearch_to_tsquery('english', $1);This parses Google-style input (
"exact phrase" -excluded OR another) without throwing syntax errors on user queries —to_tsqueryis unforgiving. -
For multilingual content, store the language with the row:
ALTER TABLE documents ADD COLUMN content_lang regconfig NOT NULL DEFAULT 'simple'; ALTER TABLE documents ADD COLUMN search_vector tsvector GENERATED ALWAYS AS ( setweight(to_tsvector(content_lang, coalesce(title, '')), 'A') || setweight(to_tsvector(content_lang, coalesce(body, '')), 'C') ) STORED;Each row’s vector is built with the right dictionary. Query-side, derive
content_langfrom the search context or use multiple queries. -
Tune GIN for high write rate:
ALTER TABLE documents SET (gin_pending_list_limit = '16MB');See GIN tuning notes.
-
Maintain. Schedule
REINDEX INDEX CONCURRENTLY documents_search_ginquarterly on busy tables — GIN bloats steadily. Pair with autovacuum andVACUUM ANALYZEto keep stats fresh.
Common pitfalls
- A misconfigured dictionary (using
englishon French content) silently returns wrong results — the query parses without error but matches nothing. Verify withSELECT to_tsvector(config, sample_text)for known content. - Stop-words (“the”, “is”) are dropped — searching for “to be or not to be” returns empty in
englishconfig. Use thesimpleconfig for verbatim search. ts_rankis slow on result sets larger than a few thousand rows because it ranks every match. Add a LIMIT and an ORDER BY with a tie-breaker.- Generated columns can’t reference other tables — denormalise the searchable fields onto the row or maintain via a trigger.
tsvectoris limited to ~1 MB per value; very long documents (entire books) need chunking.
In the engagements we run, Postgres full-text search is the answer for application-level search up to a few tens of millions of documents and a few dozen QPS. We push to a dedicated search service (Meilisearch, OpenSearch) only when we need faceting, typo-tolerance, or scale beyond what GIN can serve. The generated-column + GIN + ranking pattern is our default starting point. For the operating model behind a Postgres-led app stack, see managed operations.