Semantic search on Postgres
For engineers
Build semantic search inside one Postgres database: keyword and vector indexes, fusion, filters, speed checks and a retrieval eval before shipping.
The one-sentence idea: you can build good semantic search inside the Postgres you already run, if each index matches its query, the keyword and vector lists are fused by rank, and an eval set decides what ships.
The case
Northwind sells developer tools and keeps its product docs as 400,000 chunks in one Postgres table. Its support assistant answers questions from those chunks. Today it only uses vector search, and support engineers complain: a search for ERR_CONN_RESET 4012 returns general networking pages, and the page that names the code sits far down the list. The team wants better search without adding a new service, and the search page has a 300 ms p95 latency budget.
Why it matters
A retrieval system that is wrong looks the same as one that is right: it always returns ten results. The model then writes a confident answer from whatever it was given. Most retrieval bugs are quiet. An index that the planner never uses, a filter that empties the result list, or two scores added on different scales all produce plausible output. Only plans, traces and an eval set show them.
How to do it
1. Keyword search with built-in full-text search. Add a generated tsvector column on the chunk text and a GIN index on it. Query it with the same text search configuration that built the column, for example 'english' on both sides, or stemmed words will not match.
2. Vector search with a matching index. Store embeddings in a pgvector vector column. Pick the operator class from the embedding model's metric: vector_cosine_ops for cosine, then query with <=>. A mismatched operator, such as <-> against a cosine index, makes the planner skip the index. Build the index with CREATE INDEX CONCURRENTLY so writes keep flowing. HNSW suits a table that changes all day, because it does not need retraining as rows arrive.
3. Filters that do not starve the result. A filter such as product = 'forge' is applied after the HNSW scan finds its candidates. On a rare product, most candidates are removed and the query returns fewer rows than asked. pgvector's iterative index scans keep reading until enough rows pass.
4. Fuse by rank, not by score. Run the keyword and vector queries separately, take about 50 candidates from each, and combine them with reciprocal rank fusion (RRF): each chunk scores the sum of 1 / (k + rank) over the lists it appears in, with k = 60 as the usual constant. Ranks inside each list must come from an ORDER BY. Raw ts_rank values and cosine similarities live on different scales, so adding them lets one signal dominate.
5. Measure with an eval set. Start with real queries from the search logs, each labelled with its gold chunk, plus a few that the docs cannot answer. Report recall@k: the share of questions whose gold chunk appears in the top k. Tune settings on one part of the set and report on a held-out part.
6. Check cost in the database. EXPLAIN ANALYZE shows whether a query uses its index. pg_stat_statements shows which query uses the most total time, which is calls times mean time.
Before and after
Before: vector-only search, recall@10 of 0.71 on 200 labelled questions, and the exact error code ranked 14th.
After: keyword and vector lists fused with RRF, recall@10 of 0.83 at 85 ms p95. A cross-encoder reranker added 0.02 more recall but took p95 to 640 ms, so it waits for a faster reranker or a bigger budget.
What goes wrong
- The index is never used. The operator does not match the operator class, or the query recomputes
to_tsvectoron every row. The plan shows a sequential scan. - Scores are mixed, not ranks. A weighted sum of
ts_rankand cosine similarity looks reasonable and ranks badly. - Retrieval metrics are read as answer quality. Higher recall@10 means the right chunk is found more often. Whether the model uses it well needs a separate check on the final answers, and a trace shows which of the two failed.
- The eval set is also the tuning set. Settings chosen on the same questions that report the score overstate real performance.
What to take away
One database can carry both indexes, the fusion and the filters. The work is in matching each index to its query, fusing by rank, and letting a held-out eval set, not a demo, decide what ships.
Steps
Add keyword search inside Postgres
The team adds a generated
tsvectorcolumn and a GIN index, then confirms withEXPLAIN ANALYZEthat a search for an error code uses the index instead of a sequential scan.Keyword column and index migrations/0041_chunks_tsv.sql
ALTER TABLE chunks ADD COLUMN tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', body)) STORED;CREATE INDEX CONCURRENTLY chunks_tsv_gin ON chunks USING gin (tsv);Add vectors with an index that matches the metric
The embedding model is meant for cosine similarity, so the HNSW index uses
vector_cosine_opsand every query orders by<=>. HNSW is chosen because chunks are inserted and updated all day and no rebuild window exists.Vector index and top-10 query migrations/0042_chunks_hnsw.sql
CREATE INDEX CONCURRENTLY chunks_embedding_hnsw ON chunks USING hnsw (embedding vector_cosine_ops);SELECT id, title FROM chunksORDER BY embedding <=> $1LIMIT 10;Keep filtered queries from coming back short
Searches limited to a rare product returned 3 rows instead of 10, because the filter ran after the HNSW scan. The team turns on pgvector's iterative index scans so the scan keeps going until enough rows pass the filter.
Fuse keyword and vector lists by rank
Each method returns its top 50, ranked with an explicit
ORDER BY, and reciprocal rank fusion combines them with k = 60. A full outer join keeps chunks that only one method found.RRF query search/rrf.sql
WITH kw AS ( SELECT id, row_number() OVER (ORDER BY ts_rank(tsv, q) DESC) AS r FROM chunks, websearch_to_tsquery('english', $2) q WHERE tsv @@ q ORDER BY r LIMIT 50), vec AS ( SELECT id, row_number() OVER (ORDER BY embedding <=> $1) AS r FROM chunks ORDER BY embedding <=> $1 LIMIT 50)SELECT coalesce(kw.id, vec.id) AS id, coalesce(1.0/(60+kw.r),0) + coalesce(1.0/(60+vec.r),0) AS scoreFROM kw FULL OUTER JOIN vec ON kw.id = vec.idORDER BY score DESC LIMIT 10;Build a labelled eval set from real queries
The team takes 200 real queries from the search logs, labels each with its gold chunk, adds questions the docs cannot answer, and holds part of the set back so tuning never sees it.
Find the query that costs the most
pg_stat_statementsranks queries by total time, calls times mean. The vector top-10 query leads, so it gets attention before the rare but slow nightly re-embedding job.Let the numbers decide what ships
Hybrid search fits the 300 ms budget with a large recall gain. The reranker adds little recall for a large latency cost, so it waits. Answer quality gets its own check, because recall@10 only measures retrieval.
Variants on 200 labelled questions Variant recall@10 p95 latency (ms) Vector only 0.71 60 Hybrid (keyword + vector, RRF) 0.83 85 Hybrid + reranker 0.85 640
Skills this scenario uses
Where to study
- pgvector: open-source vector similarity search for Postgres (opens in a new tab)ToolFree
The README lists the operators, operator classes, HNSW and IVFFlat options and iterative index scans.
- PostgreSQL: Full text search (opens in a new tab)DocsFree
How tsvector, tsquery, configurations, GIN indexes and ranking work in Postgres.
- CREATE INDEX (PostgreSQL documentation) (opens in a new tab)DocsFree
What a plain index build locks and how CONCURRENTLY avoids blocking writes.
- PostgreSQL: pg_stat_statements (opens in a new tab)DocsFree
Per-query call counts and total and mean execution time, for finding the costliest query.
- Reciprocal Rank Fusion outperforms Condorcet and individual rank learning methods (Cormack et al.) (opens in a new tab)PaperFree
The original RRF paper: the formula and the constant of 60.
- Introducing Contextual Retrieval (Anthropic) (opens in a new tab)ArticleFree
Adding chunk-specific context before indexing, combined with keyword search and reranking.