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.
Learning outcomes
- Architect zero-drift generated
STOREDtsvectorcolumns (setweight(title, 'A') || setweight(body, 'B')) indexed cleanly viaGINrather than un-indexable on-the-flyto_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
pgvectorHNSW 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 / Function | Accepts Raw Untrusted User Input? | Phrase / Operator Support | Exact Behavior & Pitfall |
|---|---|---|---|
to_tsquery('english', text) | NEVER (crashes syntax error on spaces/punctuation!) | Explicit boolean AND, OR (|), NOT, and followed-by operators | Strictly for developer-constructed valid expressions |
plainto_tsquery('english', text) | Safe | ANDs all stems unconditionally | Ignores -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_cd | Cover-density proximity (ts_rank_cd) rewards tight phrase proximity cleanly | Normalization 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_chunksADD COLUMN IF NOT EXISTS fts_doc tsvectorGENERATED 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_ftsFROM knowledge_chunks, websearch_to_tsquery('english', :user_query) qWHERE tenant_id = :tenant_id AND fts_doc @@ qLIMIT 30),semantic AS (SELECT chunk_id, ROW_NUMBER() OVER (ORDER BY embedding <=> :query_vec) AS r_vecFROM knowledge_chunksWHERE tenant_id = :tenant_idORDER BY embedding <=> :query_vecLIMIT 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_scoreFROM lexical lFULL OUTER JOIN semantic s ON l.chunk_id = s.chunk_idORDER BY rrf_score DESCLIMIT 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)inWHEREWithout Indexing That Exact Expression: Recomputes tokenization sequentially over every table row cleanly instead of reading theGINindex (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"throwsSQL syntax error in tsquerycrashes cleanly in production unless wrapped inwebsearch_to_tsqueryorplainto_tsquery. - Forgetting Language Argument Alignment Across Index and Query: Creating a
GINindex with'english'while queryingwebsearch_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 withpg_trgmsimilarity (%) fallback orpgvectorsemantic 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!