FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Full-Text Search with TSVector

Native text search engine, tsvector lexeme parsing, tsquery match operators, GIN indexes, and ranking algorithms.

Freshness: current•16 min read•Data Engineering and Databases

Key Learning Outcomes

  • ✓Implement fast full-text search without external search clusters
  • ✓Rank relevance using ts_rank and GIN indexing
Full Technical Reference Document

Mental model

PostgreSQL Full-Text Search (FTS) eliminates external search cluster synchronization (Elasticsearch, Solr) cleanly for hundreds of thousands to tens of millions of documents while keeping search 100% transactional (ACID) alongside ACLs and pgvector! Postgres normalizes raw prose upfront via dictionary stemming and stopword pruning into compact sorted lexeme arrays (tsvector carrying positional coordinates and A/B/C/D importance weights), evaluated cleanly via boolean/phrase tsquery trees over GIN inverted indexes.

Generated STORED weighted tsvector (A+B)
Build GIN index over lexeme postings
Parse user input safely via websearch_to_tsquery
Fast GIN scan (`@@`) + rank (`ts_rank_cd`)
Fuse lexeme ranks cleanly via RRF + pgvector!
Conceptual teaching model synthesized from:postgresql-docs,ddia-kleppmann

Learning outcomes

  • Architect zero-drift generated STORED tsvector columns (setweight(title, 'A') || setweight(body, 'B')) indexed cleanly via GIN rather than un-indexable on-the-fly to_tsvector() scans cleanly.
  • Parse untrusted user text safely cleanly using websearch_to_tsquery (supporting quotes & -negation without crashing on malformed user boolean operators unlike raw to_tsquery)!
  • Fuse exact PostgreSQL FTS lexical matches cleanly alongside semantic pgvector HNSW results inside a single atomic SQL Reciprocal Rank Fusion (RRF) query cleanly (handling exact SKUs, error IDs, and acronyms!).

Theory

Standard SQL ILIKE '%kv cache%' forces full linear heap scans cleanly across millions of rows (unable to use standard B-Trees cleanly on leading wildcards!) and matches zero inflected variants (running misses runs). Meanwhile, calling un-indexed WHERE to_tsvector('english', body) @@ ... dynamically recomputes dictionary stemming on every single row per query (crushing CPU!). Stored generated weighted vectors paired with GIN turn lookups into sub-5ms inverted index jumps:

FTS Query Parser / FunctionAccepts Raw Untrusted User Input?Phrase / Operator SupportExact Behavior & Pitfall
to_tsquery('english', text)NEVER (crashes syntax error on spaces/punctuation!)Explicit boolean AND, OR (|), NOT, and followed-by operatorsStrictly for developer-constructed valid expressions
plainto_tsquery('english', text)SafeANDs all stems unconditionallyIgnores -negations, "quotes", and OR hints cleanly
websearch_to_tsquery('english', text)Safe & Recommended default (PG 11+)Quoted "exact phrase", OR, -exclude!Clean Google-style search parsing directly cleanly inside safe SQL
ts_rank vs ts_rank_cdCover-density proximity (ts_rank_cd) rewards tight phrase proximity cleanlyNormalization flags (32 scales cleanly 0..1)Notice ts_rank ignores corpus IDF frequency (rare terms) unless custom BM25/ParadeDB extensions run!

Remember simple vs language (english) dictionaries cleanly in technical RAG docs! Calling 'english' strips common words and stems running -> run, which works brilliantly for prose—yet 'english' splits/mutates camelCase identifiers or drops "it"/"do" tokens cleanly, so pairing 'simple' (preserving literal technical identifiers) or pg_trgm trigram fuzzy matching handles SKU/code lookups cleanly!

sql
-- 1. Weighted STORED generated tsvector combining Title (Weight A) and Body (Weight B)
ALTER TABLE knowledge_chunks
ADD COLUMN IF NOT EXISTS fts_doc tsvector
GENERATED ALWAYS AS (
setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
setweight(to_tsvector('english', coalesce(body, '')), 'B')
) STORED;
​
CREATE INDEX CONCURRENTLY idx_chunks_fts_gin ON knowledge_chunks USING gin (fts_doc);
​
-- 2. Single-query Hybrid RAG Fusion (PostgreSQL FTS + pgvector RRF cleanly under tenant ACL!)
WITH lexical AS (
SELECT chunk_id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd('{0.1, 0.2, 0.4, 1.0}', fts_doc, q) DESC) AS r_fts
FROM knowledge_chunks, websearch_to_tsquery('english', :user_query) q
WHERE tenant_id = :tenant_id AND fts_doc @@ q
LIMIT 30
),
semantic AS (
SELECT chunk_id, ROW_NUMBER() OVER (ORDER BY embedding <=> :query_vec) AS r_vec
FROM knowledge_chunks
WHERE tenant_id = :tenant_id
ORDER BY embedding <=> :query_vec
LIMIT 30
)
SELECT coalesce(l.chunk_id, s.chunk_id) AS chunk_id,
coalesce(1.0 / (60 + l.r_fts), 0.0) + coalesce(1.0 / (60 + s.r_vec), 0.0) AS rrf_score
FROM lexical l
FULL OUTER JOIN semantic s ON l.chunk_id = s.chunk_id
ORDER BY rrf_score DESC
LIMIT 10;

Trade-offs

Embedding native tsvector + GIN straight inside the same PostgreSQL cluster holding pgvector embeddings removes dual-write Elasticsearch ETL lag completely cleanly (meaning newly updated ACL permissions or document edits apply atomically cleanly in one ACID commit across lexical AND dense vector queries simultaneously!). True dedicated engines (Elasticsearch / OpenSearch / ParadeDB pg_search BM25) outscale native ts_rank strictly on true BM25 IDF term saturation math, complex multi-language phonetic stemming, and sub-millisecond typo tolerance across multi-billion-document search indices cleanly—though pairing Postgres tsvector + pg_trgm handles 90%+ of enterprise RAG applications seamlessly with minimal operational surface!

Failure modes and misconceptions

  • Calling Dynamic to_tsvector(lang, col) in WHERE Without Indexing That Exact Expression: Recomputes tokenization sequentially over every table row cleanly instead of reading the GIN index (always inspect EXPLAIN ANALYZE verifying Bitmap Index Scan on GIN!).
  • Passing Raw User Input Directly Into to_tsquery(): Typing "vLLM & OOM?" or "what is KV-cache" throws SQL syntax error in tsquery crashes cleanly in production unless wrapped in websearch_to_tsquery or plainto_tsquery.
  • Forgetting Language Argument Alignment Across Index and Query: Creating a GIN index with 'english' while querying websearch_to_tsquery('simple', ...) silently skips the index cleanly (two arguments MUST match identically!).
  • Missing Typo Fuzzy Handling & IDF Scoring (pg_trgm): Relying purely on exact stemmed lexemes misses single-character typos ("Posgresql") unless combined cleanly with pg_trgm similarity (%) fallback or pgvector semantic match cleanly.

Decision scenario

A developer RAG service querying 800,000 Postgres docs added WHERE to_tsvector('english', body) @@ to_tsquery('english', :q)—immediately causing 4-second full table scans cleanly plus HTTP 500 SQL crashes whenever users typed spaces or hyphens! Add a STORED weighted generated tsvector column (title='A', body='B') indexed cleanly via CREATE INDEX CONCURRENTLY ... USING gin, switch parsing safely onto websearch_to_tsquery('english', :q), and combine cleanly inside one atomic ACL-filtered SQL RRF hybrid fusion query alongside pgvector cleanly!

Reflect before revealing the guide

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next