How to Implement Full-Text Search in PostgreSQL
Build PostgreSQL full-text search: store a tsvector, query with tsquery, rank results, and keep the search index fresh as rows change.
On this page
Introduction
Full-text search is the difference between a search box that matches substrings and one that understands words. Matching LIKE patterns finds the letters you typed but ignores stemming, stop words, and relevance, and it cannot rank results. PostgreSQL has built-in full-text search that turns text into a normalized vector of lexemes and lets you query it with a rich language of operators and ranking functions.
This tutorial builds full-text search over a table of articles. It covers choosing a configuration, persisting and indexing a tsvector, constructing queries from user input, ranking results, and keeping the index fresh. The examples use PostgreSQL, and the same design principles apply when the search is later moved to a dedicated engine.
Choose a text search configuration
A text search configuration decides how text is parsed into tokens and how tokens are normalized. The language matters: English stems ‘running’ to ‘run’ and drops stop words like ‘the’, while other configurations apply their own rules. Pick a configuration matching the dominant content language and use it consistently, because a mismatch between the stored vector and the query means terms do not match.
If content is multilingual, either store per-language vectors and query the right one, or use a configuration that handles your mix. A simple configuration treats text as a bag of tokens without stemming, which is correct for identifiers or code and wrong for natural language. Decide deliberately, because changing the configuration later requires rebuilding every vector and index.
-- inspect how a configuration parses sample text
SELECT to_tsvector('english', 'The runners are running quickly');
-- 'run':2,3 'quick':4
SELECT to_tsquery('english', 'run & quick');
Store and index the vector
Compute the vector once and store it. A generated column keeps the vector in step with the source text automatically, and a GIN index over that vector makes searches fast. Computing to_tsvector inside the WHERE clause instead forces a sequential scan and re-parses every row, which is the most common full-text performance mistake.
The GIN index is the right choice for tsvector because it indexes the individual lexemes. Watch its size on very large tables, and consider a partial or a separate search table if you only search a subset. For phrase and proximity queries, a GiST index supports a different set of operations; choose GIN for the common case of keyword and ranking search.
ALTER TABLE articles
ADD COLUMN search tsvector
GENERATED ALWAYS AS (
to_tsvector('english', coalesce(title, '') || ' ' || coalesce(body, ''))
) STORED;
CREATE INDEX CONCURRENTLY idx_articles_search
ON articles USING gin (search);
Query and rank
Build a tsquery from user input rather than interpolating raw text. websearch_to_tsquery accepts a Google-like syntax with quoted phrases, OR, and negation, and it never raises a syntax error on arbitrary input. plainto_tsquery treats the input as a conjunction of terms, and to_tsquery requires the caller to use the query syntax correctly. Choose one according to how much power you expose.
Match with the @@ operator and order by a ranking function. ts_rank scores by term frequency, and ts_rank_cd also accounts for how close the matching terms are. Combine the rank with recency or another signal to shape relevance. Always paginate and cap the result set, because a broad query can match a large fraction of the table and the rank computation consumes work proportional to the matches.
SELECT id, title,
ts_rank_cd(search, q) AS rank
FROM articles, websearch_to_tsquery('english', $1) AS q
WHERE search @@ q
ORDER BY rank DESC, published_at DESC
LIMIT 20;
Keep the search index fresh
The generated column updates whenever the source columns change, so the index stays consistent without application code. If the vector depends on related rows, such as a post’s tags or its author’s name, a generated column cannot reference other tables, so use a trigger or a scheduled rebuild that recomputes the vector on the relevant changes. Keep the recomputation in one place so the vector is never built differently in different paths.
After bulk changes, run ANALYZE so the planner has fresh estimates for the index, and rebuild or reindex if the index has bloated. Monitor search latency and the index size as data grows, because full-text indexes are larger and slower to update than a b-tree on a scalar column, and a search feature that is fast at a million rows may need attention at a hundred million.
-- trigger to refresh the vector when a related tag changes
CREATE OR REPLACE FUNCTION refresh_article_search() RETURNS trigger AS $$
BEGIN
UPDATE articles a
SET title = a.title -- touch to force the generated column to recompute
WHERE a.id = COALESCE(NEW.article_id, OLD.article_id);
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
Test stemming, ranking, and freshness
Test that a query for ‘runs’ matches a row containing ‘running’, proving the stemming configuration is applied. Test that a multi-term query ranks a row containing both terms above a row containing one. Test that updating the body makes a new term searchable, proving the generated column or trigger refreshed the vector. These three tests cover the configuration, the ranking, and the freshness.
psql -d app -c "SELECT id FROM articles WHERE search @@ websearch_to_tsquery('english','running fast') LIMIT 5;"
# insert a row with a novel term, then search for it and assert it is found
Common pitfalls
Computing to_tsvector in the WHERE clause so the index is never used, using to_tsquery with unescaped user input so a stray operator raises an error, mismatching the stored and query configurations, indexing every language variant, and ignoring index bloat after bulk writes are the recurring mistakes. Persisting and indexing the vector, using websearch_to_tsquery for user input, aligning configurations, and monitoring the index address them.
Conclusion
PostgreSQL full-text search is a stored, indexed vector plus a query language. Choose a configuration, persist a generated tsvector, index it with GIN, build tsqueries safely from user input, rank with ts_rank_cd, and keep the vector fresh. Self-check by asserting that a stemmed form matches, that ranking orders multi-term matches first, and that an edited row becomes searchable. With those pieces, a built-in search box is fast and relevant without a separate service.
Sources: PostgreSQL: Full text search, PostgreSQL: Text search functions and operators, PostgreSQL: GIN indexes.
FAQ
- Do I need a separate search engine?
- Not always. PostgreSQL full-text search handles stemming, ranking, and phrase queries and can serve millions of rows for many workloads. Reach for a dedicated engine when you need fuzzy matching, faceting, or relevance tuning beyond what the built-in functions offer.
- Why store a tsvector instead of computing it in the query?
- A generated tsvector column can be indexed with GIN and reused across queries. Computing to_tsvector in the WHERE clause prevents the index from being used and re-parses every row on every search.
Report a problem with this articleOpens a pre-filled issue on GitHub.