Topic 1 of 5 · 4 min read
Combining BM25 keyword and vector search
Goal: Implement a hybrid query that fuses BM25 and vector results and show a query each method alone would miss.
Run keyword search and vector search side by side, then merge their ranked lists with reciprocal rank fusion (RRF), so you catch both exact terms and paraphrased meaning.
Check yourself · 1 of 3
A user searches a support wiki for ERR_CERT_9921. Which retriever is most likely to find the exact page?
Why it matters
A vector search finds text that means the same thing as the query. That is its strength and its blind spot. An embedding model has never memorised your error code E_PIPE_4017, the SKU KX-220-B or the name of a new engineer. The vector for those strings sits close to many similar-looking ones, so the right chunk can land at rank 40. Keyword search (BM25, the standard term-frequency scoring function in Elasticsearch, OpenSearch, Lucene and Postgres full text) does the opposite: it nails exact tokens and misses paraphrase. A user who types "can't sign in" will not match a chunk titled "authentication failures".
How to do it
- Run the same query through both retrievers. Ask each for the top 50 or so.
- Do not add the raw scores. BM25 scores are unbounded and vector similarities sit between 0 and 1, so one side swamps the other.
- Fuse by rank instead. RRF gives each document
1 / (k + rank)from every list it appears in, and sums them. The original paper usedk = 60. A document ranked well in both lists wins; one ranked first in a single list still scores. - Cut the fused list to the number of chunks your prompt can hold.
def rrf(lists, k=60, top=10):
scores = {}
for ranked_ids in lists:
for rank, doc_id in enumerate(ranked_ids, start=1):
scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)[:top]
fused = rrf([bm25_ids, vector_ids])
Many engines do this for you: Elasticsearch has an RRF retriever, and most vector databases ship a hybrid query.
Before and after
Query: "fix E_PIPE_4017 on deploy". Vector search alone returns three general pages on failed deployments and puts the page that names the code at rank 31. BM25 returns that page at rank 1, because the token matches exactly. After fusion it sits at rank 2 and the general pages follow it. For the query "why won't my build finish", the reverse happens: vectors find the troubleshooting guide, BM25 finds little. Fusion keeps both wins.
What goes wrong
- Adding raw scores from two scales, which lets one retriever dominate.
- Different tokenisation: the keyword index lowercases and stems, the query text goes in unprocessed, and
E_PIPE_4017is split into three tokens that match everything. - Fusing before filtering: metadata filters (tenant, language, date) must apply to both retrievers, or one list leaks documents the other excluded.
- Assuming hybrid always helps. On a corpus of pure prose questions it may add nothing. Measure it (see the measuring topic).
Examples
The same query through three retrievers
Query: refund policy for order KX-220-B.
- Vector only: returns general refund pages, the page for that SKU line is at rank 18.
- BM25 only: puts the SKU page at rank 1 but ranks a page that repeats the word "order" at rank 2.
- RRF fusion: the SKU page scores
1/61from BM25 plus1/78from vectors and wins; the general refund policy comes next.
A hybrid query as a function
def hybrid_search(q, filters, n=50, final=10):
kw = bm25.search(q, filters=filters, limit=n)
vec = vectors.search(embed(q), filters=filters, limit=n)
return rrf([ids(kw), ids(vec)], top=final)
Both calls get the same filters, so the fused list cannot include a document one side would have excluded.
Key points
- Vector search handles paraphrase but often misses exact identifiers such as error codes, SKUs and names.
- BM25 keyword search matches exact tokens but misses synonyms and rewordings.
- Fuse ranked lists by rank, not by raw score, because BM25 and similarity scores are on different scales.
- Reciprocal rank fusion sums 1 / (k + rank) across lists, with k = 60 in the original paper.
- Apply the same metadata filters and the same text normalisation to both retrievers.
Common mistakes
- Adding or averaging raw BM25 and cosine scores instead of fusing ranks.
- Indexing text with stemming for BM25 but querying with an unprocessed string.
- Applying a tenant or language filter to the vector search only.
- Shipping hybrid search without a query set that includes exact-term queries to prove it helps.
Check yourself · 2 of 3
Your BM25 scores range from 0 to 30 and your vector similarities from 0.2 to 0.9. What is the safest way to merge the two result lists?
Check yourself · 3 of 3
In reciprocal rank fusion with k = 60, a document is first in the keyword list and absent from the vector list. What is its score?
Practice items, not counted towards your mastery.
Start here
- Introducing Contextual Retrieval (Anthropic) (opens in a new tab)ArticleFree
The source of the 49% and 67% fewer failed retrievals figures, the prompt and the caching cost estimate.
- 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.
- Rerank overview (Cohere docs) (opens in a new tab)DocsFree
How a hosted rerank endpoint takes a query and documents and returns relevance scores.
More for this topic
- Reciprocal rank fusion (Elasticsearch docs) (opens in a new tab)DocsFree
A production search engine's hybrid query that fuses lexical and vector result lists with RRF.