Full-Text Search with tsvector and tsquery
LIKE '%term%' works until the table grows, the queries get complicated, and relevance suddenly matters. In-database full-text search fixes both problems.
- Lexemes, dictionaries, and configurations â what a document becomes before indexing
- Query grammar â plainto, websearch, and raw tsquery forms compared
- Ranking and highlighting â ts_rank_cd, weights, and ts_headline for snippets
- Index strategy â GIN for containment, trigram for fuzzy substrings Search is a product feature; your database can carry more of it than you think.
Prerequisites
- !Basic SQL filtering and indexing knowledge
- !PostgreSQL 14+ for the primary examples (MySQL FULLTEXT differences are covered below)
- !Comfort with casting and function syntax
What You'll Learn
- 1Convert documents and queries into tsvector and tsquery values
- 2Rank and highlight results so search feels useful, not just correct
- 3Choose the right index â GIN, GiST, or trigram â for each query shape
- 4Recognize when full-text search is the wrong tool and an external engine is better
What Full-Text Search Actually Does
A full-text engine reduces a document to a multiset of lexemes â normalized word forms produced by a dictionary. The English dictionary stems "running" and "runs" to "run", folds case, and drops stop words like "the" depending on configuration. The resulting value is a tsvector, an ordered, deduplicated list of lexemes with positions. Queries become tsquery trees of lexemes combined with & (and), | (or), and ! (not), plus prefix matches written foo*.
Matching a query against a document then becomes set containment instead of substring scanning, which is both faster with the right index and semantically smarter: "searching for run" finds "running" without wildcard tricks. Ranking layers on top, scoring each hit by lexeme rarity and proximity so better matches float to the top.
The trade-offs are real. Analysis strips inflection, so exact product codes can be mangled by stemming. Languages need matching dictionaries â the default configuration for English will not segment other languages sensibly. And full-text search is not a typo-tolerant, synonym-aware, learning-to-rank web search engine; it is a solid middle layer between LIKE and a dedicated search service.
Building tsvector and tsquery Values
PostgreSQL exposes constructor functions for both sides of the match. Prefer websearch_to_tsquery for user input: it supports quoted phrases, -exclusions, and bare OR keywords with the same syntax people already know from web search boxes.
-- Documents and queries converted to lexeme space
SELECT to_tsvector('english', 'The batteries run for twelve hours on a single charge');
SELECT to_tsquery('english', 'battery & run & !charger');
SELECT websearch_to_tsquery('english', '"twelve hours" OR autonomy -charger');
-- plainto_tsquery: all terms ANDed, no operator syntax
SELECT plainto_tsquery('english', 'twelve hour battery');
| Function | Input | Behavior |
|---|---|---|
to_tsvector | Document text | Stems, lowercases, drops stop words per configuration |
to_tsquery | Query with operators | Powerful but unforgiving â malformed input raises errors |
plainto_tsquery | Raw user text | Safe: ANDs all terms, no operator interpretation |
websearch_to_tsquery | Web-style query string | Phrases, OR, and minus exclusions; best default for UI input |
phraseto_tsquery | Quoted phrase | Requires terms in order with adjacency |
Store the tsvector alongside the document â physically in a generated column or lazily via a trigger â so it can be indexed. Postgres 12+ supports generated columns for many expressions, but tsvector generation with custom configurations is often kept in an IMMUTABLE expression index instead.
-- A searchable articles table with generated vector and GIN index
CREATE TABLE articles (
article_id BIGSERIAL PRIMARY KEY,
title TEXT NOT NULL,
body TEXT NOT NULL,
published_at DATE NOT NULL DEFAULT CURRENT_DATE,
search_vector TSVECTOR
GENERATED ALWAYS AS (
setweight(to_tsvector('english', title), 'A') ||
setweight(to_tsvector('english', body), 'B')
) STORED
);
CREATE INDEX idx_articles_fts ON articles USING GIN (search_vector);
-- Weighted search: title matches outrank body matches
SELECT
article_id,
title,
ts_rank_cd(search_vector, query) AS rank,
ts_headline('english', body, query, 'StartSel=<b>, StopSel=</b>, MaxFragments=2, MaxWords=40') AS snippet
FROM articles, websearch_to_tsquery('english', 'database indexing') AS query
WHERE search_vector @@ query
ORDER BY rank DESC
LIMIT 20;
The setweight call assigns each lexeme a weight class (A is highest, D lowest) based on which field it came from. That single line is the cheapest relevance improvement most applications can make: a title hit should outrank a passing mention in the body, and the ranking function knows nothing about your content unless you tell it.
Ranking, Highlighting, and Query UX
Two ranking functions ship with PostgreSQL. ts_rank scores by frequency and density; ts_rank_cd (cover density) additionally rewards lexemes that appear close together, which better matches human expectations for phrase-like queries. Both accept an option integer to select normalization behavior â normalizing by document length prevents long documents from dominating purely by having more words.
ts_headline builds the snippet shown under each result: it locates the matching terms inside the original text and wraps them in markers you choose. Its default configuration is usable; production code should set MaxWords, MinWords, MaxFragments, and explicit StartSel/StopSel so output is safe to drop into HTML without post-processing surprises.
Design details that separate toy search from usable search:
- Accept the user's raw string and pass it through
websearch_to_tsquery, never string-assemblytsquerysyntax. - Surface zero-result queries; they are free product research.
- Consider partial matching for short queries â single short words often benefit from prefix
lexeme*form, capped by a minimum length to protect index performance. - Combine full-text results with recency or business boosts in the ORDER BY, for example
rank + (published_at > CURRENT_DATE - 30) * 0.5.
Index Choices: GIN, GiST, and Trigram
The default index for tsvector columns is GIN. GIN indexes inverted entries and answers containment questions efficiently, at the cost of slower writes and larger size. GiST indexes are an alternative with faster updates and smaller footprint in some workloads, but typically slower lookups. Choose GIN for read-heavy search tables; measure GiST when write volume dominates.
Full-text search does not help with substring matching â finding "audit" inside "continuous" â because lexemes are whole words. For substrings, typos, and fuzzy matching, enable the pg_trgm extension and index with a trigram GIN index:
-- Trigram support for fuzzy and substring matching
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_products_trgm ON products USING GIN (name gin_trgm_ops);
-- ILIKE now becomes an indexable operation
SELECT product_id, name
FROM products
WHERE name ILIKE '%continu%'
ORDER BY similarity(name, 'continu') DESC
LIMIT 10;
Trigram indexes and full-text indexes solve different problems and happily coexist: FTS for word-level search, trigram for substrings and fuzzy fallback when FTS returns nothing.
MySQL FULLTEXT in Brief
MySQL 8 offers FULLTEXT indexes on CHAR, VARCHAR, and TEXT columns with two modes. Natural language mode ignores operators and ranks by term frequency against a document-frequency table. Boolean mode understands +required, -excluded, *prefix, and quoted phrases â roughly the role tsquery plays in PostgreSQL. The ngram parser handles space-delimited languages where word boundaries are not marked by spaces.
-- MySQL 8: FULLTEXT index and boolean-mode query
CREATE FULLTEXT INDEX idx_articles_fts ON articles (title, body);
SELECT
article_id,
title,
MATCH(title, body) AGAINST ('+database +index -mysql' IN BOOLEAN MODE) AS score
FROM articles
WHERE MATCH(title, body) AGAINST ('+database +index -mysql' IN BOOLEAN MODE)
ORDER BY score DESC
LIMIT 20;
MySQL's FULLTEXT has practical limits worth knowing before committing to it: a minimum word length (innodb_ft_min_token_size, default 3) and a built-in stop-word list that must be checked when results mysteriously miss short terms.
When to Reach Beyond the Database
In-database full-text search covers a lot of ground: product catalogs, documentation sites, internal knowledge bases, and log search at moderate scale. Reach for Elasticsearch, OpenSearch, Meilisearch, or a similar engine when you need typo tolerance by default, synonym graphs, per-user relevance tuning, faceting at massive scale, or distributed sharding managed by a search specialist team. A pragmatic architecture for many products is a Postgres full-text core with an external engine added only when the feature list demands it â keeping one source of truth and avoiding premature operational complexity.
Common Mistakes
Passing raw user input into to_tsquery and crashing on stray characters
Fix: Use websearch_to_tsquery or plainto_tsquery; they sanitize automatically
Indexing without setweight and wondering why ranking feels random
Fix: Weight title and body differently so field importance reaches the rank function
Expecting full-text search to match substrings inside words
Fix: Add pg_trgm GIN indexes for substring and fuzzy needs; FTS matches whole lexemes
Using the default English configuration for other languages
Fix: Create a text search configuration with the matching dictionary and apply it consistently
Calling to_tsvector inside the WHERE clause without an expression index
Fix: Store the vector (generated column or trigger) and index the stored column with GIN
Best Practices
- Default to websearch_to_tsquery for anything fed from a user interface
- Store tsvector values physically and index them with GIN for read-heavy tables
- Use ts_headline for snippets instead of slicing strings in application code
- Log zero-result queries and treat them as a backlog of synonym or dictionary work
- Benchmark against realistic document sizes â small test tables hide ranking and index costs
Interview Questions
Q1: What is the difference between plainto_tsquery and websearch_to_tsquery?
plainto_tsquery treats the entire input as plain words and ANDs them together, supporting no operators. websearch_to_tsquery additionally understands quoted phrases, OR keywords, and -exclusions, mirroring web search box syntax safely.
Q2: Why does a title match often need setweight to rank above a body match?
ts_rank scores lexeme frequency and proximity, not field importance. setweight assigns weight classes to lexemes from each field so the rank function can boost title hits relative to body hits.
Q3: When would you choose pg_trgm over a full-text index?
When queries match substrings, require fuzzy or misspelling tolerance, or use ILIKE patterns. Full-text indexes operate on whole lexemes and cannot answer contains-substring questions.
Key Takeaways
- tsvector is analyzed text; tsquery is a boolean tree of lexemes; @@ tests the match
- websearch_to_tsquery is the safe default for user-supplied queries
- Weighted fields plus ts_rank_cd produce rankings that match human expectations
- GIN indexes power FTS lookups; trigram indexes cover substrings and fuzzy matching
- Full-text search is a strong middle layer â external engines earn their complexity only at greater scale or feature need