Sub topic 11
Hybrid search: combining BM25 and vector results
This chapter assumes you can run basic Python, know what an embedding is, and have built a top-k vector search like the one in the earlier chapters. You should also know the basic idea of keyword search.
Why combine two retrievers
Vector search matches meaning. It is good at "reset my password" versus "recover account access". It is weaker on exact strings such as error codes, product names, or rare identifiers. A query like ERR_4012 may land near unrelated text, because the embedding model never learned that token well.
BM25 is a keyword ranking function. It scores a document by how many query words it contains, how rare those words are across the collection, and how long the document is. It is strong on exact terms and blind to synonyms.
Hybrid search runs both retrievers and merges the two ranked lists. Each retriever covers the other's weak spot.
The score scale problem
The obvious approach is to add the two scores. This fails because the scales differ. BM25 scores are unbounded and depend on the collection and the query. Cosine similarity falls between -1 and 1. Adding them lets one retriever dominate. You can normalize each score list first, for example with min-max scaling, but a single outlier changes every normalized value, and the weights need tuning.
Reciprocal rank fusion
Reciprocal rank fusion (RRF) avoids the problem by ignoring scores. It uses only each document's rank position. A document at rank r in one list earns 1 / (k + r) points, and points are summed across lists. The constant k is commonly 60. It limits how much the very top ranks dominate.
def reciprocal_rank_fusion(rankings, k=60):
"""rankings: list of ranked lists of document ids, best first."""
scores = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
keyword_ranking = ["d3", "d1", "d7"]
vector_ranking = ["d1", "d5", "d3"]
print(reciprocal_rank_fusion([keyword_ranking, vector_ranking])) # ['d1', 'd3', 'd5', 'd7']Work through the result. Document d1 is rank 2 in the keyword list and rank 1 in the vector list, so it scores 1/62 + 1/61. Document d3 is rank 1 and rank 3, so it scores 1/61 + 1/63. The first sum is larger, so d1 wins. Documents d5 and d7 each appear in only one list, so they trail the documents both retrievers found. A document found by both retrievers is rewarded, which is the behavior you want.
Using it in practice
- Retrieve a generous candidate set from each retriever, such as the top 50. Fusion cannot promote a document that neither list contains.
- Pass the ranked id lists to
reciprocal_rank_fusion. - Keep the top few fused results, or hand them to a reranker, covered in the next chapter.
To favor one retriever, you can repeat its list in the input or multiply its contribution by a weight. Start unweighted and change this only if evaluation shows a gain.
Common errors
- Fusing scores directly without normalizing.
- Retrieving too few candidates per retriever, so the lists barely overlap.
- Assuming hybrid always wins. On a collection with conversational queries and no rare identifiers, vector search alone can match it. Measure with recall@k and MRR on labeled queries.
Exercise
Using k=60, a document is at rank 1 in the BM25 list and absent from the vector list. Another document is at rank 5 in both lists. Which has the higher RRF score?
Show answer
The first scores 1/61, about 0.01639. The second scores 2/65, about 0.03077. The second wins because RRF sums contributions from both lists, so agreement between retrievers outweighs one top rank.