Contents
In brief
A parts counter sees two customers. One reads RP-4471-B off the box. The other says the order never arrived. Keyword search is the label drawer. Vector search is the clerk who recognizes the complaint. Hybrid search puts both of them on the same shelf, in the Postgres the app already runs.
Two years ago the author would have opened a dedicated vector database first. pgvector is now the starting point for most web apps up to a few million chunks. The text and the vector sit on one row and commit together. A deleted document cannot leave its vector behind. A renamed product cannot keep matching the old description.
What happened
The write-up is the schema the author actually runs: chunk-level retrieval inside the existing Postgres. How you cut the document before you embed it decides retrieval quality more than the formula that later merges the lists.
The lexical branch catches strings that carry no meaning. Part numbers, ERR_CONNECTION_TIMED_OUT, invoice references, three-letter acronyms that change with the tenant. websearch_to_tsquery builds the query, a generated content_tsv column matches it, and ts_rank_cd ranks the hits. Keep the first 50.
The vector branch catches the paraphrase. A question about a lagging Postgres replica misses a note titled around replication lag when the words do not line up. A question about vehicle maintenance lands near a note about an oil change, because the vectors sit close. Embed the same text and order embedding with the cosine operator <=>. Another 50.
You cannot add a ts_rank_cd score to a cosine distance. The scales differ, and min-max normalization over one result set shifts on the next query. Reciprocal rank fusion throws the raw scores away and keeps the place in each list. A hit scores 1 / (k + rank) from each branch that found it. k is usually 60, the constant from the original paper.
A document near the top of both lists beats a document that is first in only one. At k = 60 the head of each list is compressed: top ranks contribute something between 1/61 and 1/110. Drop k below about 20 and the first hit of either branch swamps the rest.
One empty branch is normal. A full outer join still returns whatever the other branch found. The score is then a single term, about half of a two-branch hit. That is fine inside one result set. It is not comparable across queries, so do not log it as a quality metric.
The sample query takes three parameters: the raw text, the tenant, and the query vector.
People search for documents, not passages. DISTINCT ON (document_id) keeps the best chunk of each document and returns ten. Without that collapse, ten slices of one handbook fill the page.
On Postgres 12 and later the planner can inline a common table expression that is not marked MATERIALIZED. The cap of 50 rows stops being a fence. Mark the expression and keep the LIMIT inside it.
Embed chunks, not whole documents. A 40-page handbook averaged into one vector matches everything weakly and nothing precisely. Fusion can only reorder what it was given, so each branch must hand over more candidates than you show.
Two tables. documents is what a person sees: title, source address, tenant, updated time. chunks is what you search: text, position, the same tenant, vector(1536), and a model column defaulting to text-embedding-3-small. Document plus chunk index is unique. Deleting a document cascades to its chunks.
content_tsv is generated with to_tsvector('english', content) and stored. You cannot set it by hand, so the search text cannot drift from the body. The model column records which model produced the vector. After a model change you can see the stale rows, and the rebuild stays a targeted fill instead of an unbounded pass.
The vector index is HNSW with cosine ops, starting at m = 16 and ef_construction = 64. The text column gets a GIN index. Plain indexes cover document and tenant.
Why it matters
The point of staying in PostgreSQL is three properties you lose the moment the row and its vector live in different systems.
Text and vector commit together. There is no dual-write queue and no nightly reconciliation. The usual scar of two systems is a deleted document whose vector survived the cascade, or a renamed product whose vector still describes the old card.
Tenant isolation and permissions stay WHERE clauses in the same plan. Soft delete and publication state do too. You are not keeping a second description store in step with the index.
Backup, replicas, and the connection pool stay what they already were. You still operate one database.
This is where the result list goes quiet. An approximate index walks the graph first. The filter runs on whatever that walk returned. The pgvector docs state the consequence: if the predicate matches 10% of rows and hnsw.ef_search is at its default of 40, about four rows survive. A tenant query on a shared table is often that selective. Fusion then has almost nothing to add up.
Same counter. The clerk pulls the forty nearest boxes in the whole warehouse, then checks the shop sticker. The shop is a tenth of the stock. Four boxes land on the counter.
Which repair you pick depends on how many distinct filter values you have. Iterative scans arrived in pgvector 0.8.0. SET LOCAL hnsw.iterative_scan = relaxed_order keeps walking until enough rows pass the filter or the walk hits hnsw.max_scan_tuples, 20,000 by default. relaxed_order may disturb distance order a little and return more. strict_order keeps the order and costs more. IVFFlat has ivfflat.iterative_scan and ivfflat.max_probes.
A partial HNSW index per tenant is reasonable when you have about five large tenants. Five thousand small ones would multiply indexes. Past a few million chunks, partition the table by tenant. The planner skips the other partitions, and vacuum stops fighting one giant graph.
Raise hnsw.ef_search for one transaction with SET LOCAL, not for the whole server. A global setting leaks through the pool and slows every query, including the ones that do not need a longer walk. The author's example sets 100 for the transaction.
HNSW and IVFFlat are both approximate, and they fail differently. For steady writes and a search box that cares about milliseconds, use HNSW. New rows join the graph. Recall at the same latency is usually higher without a long tuning pass. The build costs more and uses maintenance_work_mem.
IVFFlat builds faster and lighter. Inserts after the build decay until you rebuild. It fits a large, mostly static corpus. Start with about rows / 1000 lists up to a million rows, then the square root of the row count. Keep probes near the square root of the list count. The query knob is ivfflat.probes.
The memory sum is unforgiving. A 1536-dimension single-precision vector is 1536 × 4 = 6144 bytes before page overhead. A million chunks is about 6.1 GB of raw vectors, plus roughly 128 bytes of graph links per node at m = 16. Single-digit millisecond reads need that working set in RAM.
Two levers come before a bigger server. halfvec stores half precision, 3072 bytes at the same dimensionality, and you can index the cast while the full vector stays on disk. binary_quantize packs those 1536 dimensions into 192 bytes. Use it as a first pass, then rerank the top 200 with full precision.
Build the index after the data is loaded. An HNSW index created on an empty table and then fed a million rows makes a worse graph than one built over the rows you already have. CREATE INDEX CONCURRENTLY does that on a live table without blocking writes. If Postgres says the graph no longer fits in maintenance_work_mem, believe it. Raise the setting for the build session, or accept a slow build.
What shows up after launch is absent from the demo. Overlapping chunk windows produce near-duplicate rows that both score well. Dedupe at write time with a content hash per document, or the same paragraph comes back twice. A chunk from the middle of a document does not know it is supporting material. If the title matters, put it in the chunk text before you embed, not after retrieval.
There is also a measurement question. If every hybrid win was already a correct keyword answer, the vector branch spends embedding calls and index memory, and the person at the search box gains nothing.
In practice
Size the working set first. Chunks times bytes per vector, plus the graph links, have to fit in RAM with headroom for Postgres itself. If the number does not fit, you are in a partitioning or quantization conversation, not a hardware one.
Add the columns and a nightly fill before you touch the query path. Users see no change yet. Build indexes without blocking writes, then read the plan on a real query. EXPLAIN (ANALYZE, BUFFERS) with a real tenant id should use both indexes, not a sequential scan.
Build a golden set of 50 to 100 queries from your own logs. Each one carries the document ids a person would accept. Score four setups: lexical only, vector only, hybrid at k = 60, and hybrid with a reranker in front.
| What to report | Why |
|---|---|
Recall@10 |
Share of queries where an acceptable document appears in the first ten. Position 11 is a miss for a search box |
MRR@10 |
Rewards putting the right document first, not tenth |
| p95 latency | At production hnsw.ef_search, on your hardware, with the pool saturated |
| Which branch produced the opened hit | If hybrid wins were already lexical wins, the vector branch is only occupying memory |
Write two budgets down before launch. p95 under 150 ms for a search box a person actually uses. Recall at ten within two points of the best setup you tested. If you cannot hit both, lower ef_search and see what recall you give up. Add another system after that measurement, not instead of it.
Cut over behind a flag and keep the old path. Remove the dedicated search system after a month of comparable recall and a better p95.
Changing embedding models is a schema migration whether or not anyone calls it one. New dimensions, a new distance distribution, a full re-embed of every chunk. Doing it in place takes search offline. Add a second column and index, fill in batches, dual-write both vectors for new text, and flip a read flag. Drop the old path once the new one has proved itself on the golden set.
In the example the second column is halfvec(1536), indexed with halfvec_cosine_ops at the same m and ef_construction, with progress in model_v2. Keep batches small enough that autovacuum keeps up. A failed run resumes instead of restarting. Run ANALYZE after the fill and again after the cutover. The planner's estimates for the new index start from nothing.
Takeaway
Hybrid search in Postgres is a schema, a rank fusion, and a habit of measuring. The schema keeps text and vector from drifting across two systems. Fusion turns two incompatible scales into one order without normalizing anything. Measurement stops you from shipping a meaning branch that costs memory and changes nothing for the person at the search box.
Get the filtered walk wrong and the counter is back to four boxes. Get the walk far enough that the tenant filter does not eat the candidates, and both the part number and the missing-order complaint take the same path, in one database, with one backup.



Comments