How to Implement Hybrid Search with BM25 and Vectors
Combine lexical BM25 search with dense vector retrieval and fuse the rankings so keyword and semantic queries both return relevant results.
On this page
Introduction
Keyword search and vector search fail in opposite ways. A BM25 index nails exact tokens, rare identifiers, error codes and product names, but misses paraphrases: a user who types “how do I stop the connection from dropping” will not match a document that says “keep-alive tuning”. A dense embedding index understands paraphrase and synonymy, but it blurs rare tokens, so a search for an exact part number or a stack trace can return semantically plausible noise. Hybrid search runs both retrievers and merges their result lists, which gives you the precision of lexical matching and the recall of semantic matching in one query. This tutorial builds that pipeline end to end.
Why a Single Retriever Is Not Enough
BM25 scores a document by term frequency, inverse document frequency and length normalisation. It is exact in the sense that it rewards the literal query terms that appear in the document, which is exactly what you want for identifiers, names and quoted phrases. Its weakness is vocabulary mismatch: if the query and the document share no tokens, BM25 returns nothing, no matter how related the meaning is.
A dense retriever embeds the query and every document into a shared vector space and ranks by cosine similarity or inner product. It handles synonymy and paraphrase, and it can generalise across languages that share an embedding model. Its weakness is the opposite: rare tokens are mapped to roughly the same region as common ones, so an exact code is not privileged. Because the two failure modes are complementary, running them together and fusing the scores reliably beats either one alone.
Building the Lexical Retrieval Step
The lexical step lives in the database where the documents already are. PostgreSQL’s full-text search gives you a tsvector column, a GIN index and the ts_rank function, which is a BM25-like ranking that is good enough for most corpora. Keep the configuration explicit so the tokenizer behaviour is stable, and query it with websearch_to_tsquery so user input is parsed safely rather than interpolated into the query string.
One detail that matters in production is the rank normalisation. Raw ts_rank values are unbounded and their scale depends on the corpus, so you cannot add them to a cosine score directly. Select a fixed number of candidates (for example the top fifty) and convert each result list into a rank-based score before fusion.
-- Lexical retrieval: top candidates by ts_rank (BM25-like).
SELECT id,
ts_rank(tsv, query) AS lexical_score,
ROW_NUMBER() OVER (ORDER BY ts_rank(tsv, query) DESC) AS lexical_rank
FROM documents, websearch_to_tsquery('english', $1) AS query
WHERE tsv @@ query
ORDER BY lexical_score DESC
LIMIT 50;
Building the Vector Retrieval Step
The semantic step uses an approximate nearest-neighbour index such as HNSW over a vector column. Query it with the same embedding model you used to index the documents; mixing models silently degrades quality because the two vectors occupy different spaces. Retrieve a candidate pool of the same size as the lexical step so the fusion sees comparable lists.
Set the HNSW ef_search parameter high enough to keep recall near the exact search result, and measure recall against a brute-force scan on a sample before you trust the approximate index. If recall is poor, the vector retriever returns a misleading candidate list and no amount of fusion will fix it.
-- Vector retrieval: nearest neighbours by cosine distance.
SET hnsw.ef_search = 100; -- trade latency for recall
SELECT id,
1 - (embedding <=> $2::vector) AS vector_score,
ROW_NUMBER() OVER (ORDER BY embedding <=> $2::vector) AS vector_rank
FROM documents
ORDER BY embedding <=> $2::vector
LIMIT 50;
Fusing Rankings with Reciprocal Rank Fusion
Reciprocal Rank Fusion (RRF) merges result lists without needing the scores to be on the same scale. For each document it sums 1/(k + rank) across the lists that contain it, where k is a smoothing constant, typically 60. A document ranked first in both lists scores higher than one ranked first in only one list, so agreement is rewarded, and a document that only one retriever found still surfaces if its rank is high.
RRF is robust precisely because it throws away the raw scores, which are the part that is hardest to calibrate. If you later want to use the scores, normalise each list with min-max scaling or a z-score before combining, and validate the fusion weights against a labelled set rather than guessing. Start with RRF; reach for weighted score fusion only when you have relevance judgements to tune it.
// Reciprocal Rank Fusion over two ranked lists of ids.
function reciprocalRankFusion(lists, k = 60) {
const scores = new Map();
for (const list of lists) {
list.forEach((id, index) => {
const contribution = 1 / (k + index + 1);
scores.set(id, (scores.get(id) ?? 0) + contribution);
});
}
return [...scores.entries()]
.sort((a, b) => b[1] - a[1])
.map(([id, score]) => ({ id, score }));
}
const fused = reciprocalRankFusion([lexicalIds, vectorIds]);
console.log(fused.slice(0, 10)); // fused top-10 across both retrievers
Choosing Candidate Pools and Fusion Depth
Retrieve deeper than you intend to return. If the final page shows ten results, fetch fifty to one hundred candidates from each retriever so fusion has material to work with; a document ranked eleventh by the vector retriever could still be the best answer once the lexical list is folded in. Deeper pools cost latency, so measure the trade-off and pick a depth where recall stops improving.
Fusion depth and reranking interact. A cheap first stage (BM25 plus vectors) narrows thousands of documents to a few hundred; an expensive cross-encoder reranker then rescores the top fifty to improve precision. Never send thousands of documents to a cross-encoder, because its cost is linear in the number of candidates and it will dominate your latency budget.
Evaluating Hybrid Versus Each Retriever
You cannot tell whether hybrid search helps without a labelled query set. Build a set of real queries with known-relevant documents, then report recall@k and mean reciprocal rank for BM25 alone, vectors alone, and the fused result. The point of hybrid is to lift the worst-case query, so look at queries where one retriever fails badly and confirm the fusion rescues them.
Track metrics per slice, not just in aggregate. Queries containing identifiers, quoted phrases or rare names should favour the lexical retriever and should not regress when you enable fusion; open-ended natural-language questions should favour the vector retriever. If a slice regresses, tune the candidate depth or the fusion constant rather than abandoning the approach.
# Example evaluation summary (illustrative numbers)
retriever recall@10 mrr
bm25 0.62 0.48
vectors 0.71 0.55
hybrid (rrf k=60) 0.83 0.64
identifier queries: bm25 wins alone, hybrid preserves it
paraphrase queries: vectors win alone, hybrid lifts recall
Common Pitfalls and Limitations
The most common failure is inconsistent tokenisation between indexing and query time, for example indexing with one language configuration and querying with another. That silently breaks the lexical retriever. The second is embedding drift: re-embedding documents with a new model version without re-embedding the whole corpus leaves half the vectors in an incompatible space.
Also watch for score-scale mistakes. Adding a raw ts_rank to a raw cosine distance produces a number dominated by whichever retriever happens to have the larger range, which quietly reduces hybrid search to single-retriever search. RRF avoids this, and any score-based fusion must normalise first. Finally, hybrid search adds latency because it runs two queries; budget for it and enforce a deadline so one slow retriever cannot stall the whole request.
Conclusion
Hybrid search pairs a lexical retriever that is precise on rare tokens with a dense retriever that is robust to paraphrase, then fuses their rankings with RRF so agreement is rewarded and raw score scales stop mattering. Build both steps against the same candidate depth, normalise or rank-fuse rather than adding raw scores, and validate with a labelled query set sliced by query type. Done well, hybrid search is the difference between search that answers the query the user typed and search that answers the query the user meant.
Sources: PostgreSQL: Full Text Search, Reciprocal Rank Fusion (Cormack et al.), pgvector: HNSW index.
FAQ
- Is a reranker required for hybrid search to work?
- No. Fusion alone improves recall over either retriever, and a reranker is a precision refinement you add when latency budget allows. Start with BM25 plus vectors plus RRF, measure, then add a cross-encoder over the fused top fifty only if precision is the bottleneck.
- Why does RRF ignore the retrieval scores?
- The scores from different retrievers are on incompatible and often unbounded scales, so adding them mixes arbitrary units. RRF uses only ranks, which are comparable across retrievers, making it robust without calibration. Use score fusion only when you can normalise the scores against labelled data.
Report a problem with this articleOpens a pre-filled issue on GitHub.