Learning path: Build and Measure a RAG System · Step 7 of 9
Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
One customer types an error code, another describes the problem. BM25 nails the code and misses the meaning; dense search does the opposite. Run both over 12 help articles, see why adding scores fails, and merge the ranks with Reciprocal Rank Fusion so all three test searches come out right.
What you will learn
- Explain why BM25 finds exact codes and dense search finds meaning
- Run both searches over the same articles with rank_bm25 and sentence-transformers
- See why adding raw scores picks the wrong article
- Merge two ranked lists with Reciprocal Rank Fusion, 1 / (60 + rank)
Before you start
- Real Embedding Models
- TF-IDF with TfidfVectorizer
If retrieval misses the right piece, the model never sees it. Hybrid search makes retrieval better with a simple idea: run two different searches over the same documents, then merge their ranked lists into one. The two searches are BM25 and dense search, and the merge is called fusion.
Trust who both rank high
Two detectives look at the same five suspects. The first goes by fingerprints, exact matches only, and puts suspect C first. The second goes by motive, what the story means, and puts B first with C right behind. Who do you trust? Suspect C, near the top of both lists. That's the whole idea of hybrid search.
One help centre, two kinds of searcher
A help centre has 12 short articles (synthetic, written for the lesson). Customers search them two ways:
- Some type a code: error E-4072. That code sits inside article A01, Checkout stops with a bank message.
- Some describe the problem: my card was refused. They need A05, Why a payment is declined. The word "refused" isn't in any article; A05 says "decline".
A code needs the exact word. A description needs the meaning. One method can't do both.
BM25: count words, rare words count more
BM25 splits the query into words and checks which articles contain each one, with a weight that depends on how rare the word is. (It's a cousin of TF-IDF.) On these 12 articles:
| Query word | In how many articles | Weight |
|---|---|---|
| error | 4 of 12 | 0.64 (common, small) |
| e-4072 | 1 of 12 | 2.04 (rare, about three times bigger) |
| refused | 0 of 12 | 0 (no match, no score) |
BM25 simply can't tell that "refused" means "declined".
Both searches in code
retrievers.py builds both indexes once, at startup:
import re
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer, util
from articles import ARTICLES
IDS = [a[0] for a in ARTICLES]
TEXTS = [f"{title}. {body}" for _, title, body in ARTICLES]
def words(text):
# the dash stays in the pattern, so e-4072 is one word
return re.findall(r"[a-z0-9-]+", text.lower())
bm25 = BM25Okapi([words(t) for t in TEXTS])
model = SentenceTransformer("all-MiniLM-L6-v2")
doc_vectors = model.encode(TEXTS)
def bm25_ranking(query):
scores = bm25.get_scores(words(query))
return sorted(zip(IDS, scores), key=lambda p: -p[1])
def dense_ranking(query):
scores = util.cos_sim(model.encode(query), doc_vectors)[0].tolist()
return sorted(zip(IDS, scores), key=lambda p: -p[1])
words lowercases and splits, keeping the dash, so e-4072 stays one word. get_scores adds up the parts for each query word: A01 gets 0.57 for "error" plus 1.83 for the code, 2.40 in all. Dense search turns each article into 384 numbers once, then compares the question's vector with all 12 using cosine similarity. Both functions return all 12 articles, sorted, rather than a top few. That matters for fusion.
Each method fails once
hybrid.py prints the top 3 of each list. The code search:
== error E-4072
BM25 1 A01 Checkout stops with a bank message 2.40
BM25 2 A02 Error E-4027: session expired 0.96
BM25 3 A03 Error E-4720: no permission 0.90
Dense 1 A04 Error E-4702: a server fault 0.63
Dense 2 A01 Checkout stops with a bank message 0.55
Dense 3 A02 Error E-4027: session expired 0.48
BM25 is right. Dense puts A04 first: E-4072 and E-4702 differ by two swapped digits, and to an embedding model they look almost the same.
== my card was refused
BM25 1 A06 Redeem a gift card 2.32
BM25 2 A05 Why a payment is declined 1.70
BM25 3 A01 Checkout stops with a bank message 0.00
Dense 1 A05 Why a payment is declined 0.64
Dense 2 A09 Get a refund 0.33
Dense 3 A01 Checkout stops with a bank message 0.32
Now BM25 is wrong: A06, the gift card article, wins only because it keeps using the word "card". Dense is right, at 0.64, with the next one at only 0.33. No shared word between "refused" and "declined", but the meaning is close.
Why not add the scores?
Take the two articles from the last search. BM25 scores go up to 2.32; cosine scores stay under 1. Add them, and A06 (2.32 from BM25) gets 2.63 in total, while A05 gets 1.70 + 0.64 = 2.34. The wrong article wins, because the bigger BM25 scale drowns out dense.
So we ignore the scores and use the ranks. A05 is 2nd and 1st. A06 is 1st and 4th. Scores have different scales, but a rank is always a rank.
Reciprocal Rank Fusion
from retrievers import IDS, bm25_ranking, dense_ranking
K = 60
def rrf(*rankings, k=K):
"""Reciprocal Rank Fusion: each list gives 1 / (k + rank)."""
score = {i: 0.0 for i in IDS}
for ranking in rankings:
for rank, (article_id, _) in enumerate(ranking, start=1):
score[article_id] += 1 / (k + rank)
return sorted(score.items(), key=lambda p: -p[1])
Each list gives every article 1 / (60 + rank). Rank 1 gives 0.0164; rank 10 still gives 0.0143. The 60 keeps the gaps small, so no single list can dominate.
The BM25 list goes through the loop first, then the dense list adds its points on top. A05 climbs to 0.0325; A06 stops at 0.0320. The last line sorts them, and A05, the right article, moves to the top.
Hybrid gets all three
Hybrid 1 A01 Checkout stops with a bank message 0.0325
Hybrid 2 A04 Error E-4702: a server fault 0.0320
Hybrid 3 A02 Error E-4027: session expired 0.0320
That's the code search, fused. Over the three test searches:
| Query | Right article | BM25 | Dense | Hybrid |
|---|---|---|---|---|
| error E-4072 | A01 | yes | no | yes |
| my card was refused | A05 | no | yes | yes |
| reset my password | A07 | yes (5.21) | yes (0.60) | yes (0.0328) |
The password question is the easy one, and fusion doesn't break what already works. Each method fails once; hybrid gets all three. Three queries is a demo, not a benchmark: to compare retrievers properly, score them on a golden set, as in Retrieval Evals.
Common mistakes
- Adding or averaging raw BM25 and cosine scores. Different scales; the bigger one wins.
- Fusing only the top 3 of each list. An article missing from a list gets no points from it; pass the full rankings (or a generous top-k).
- A tokenizer that splits codes apart.
e-4072must stay one word, or BM25 loses its best clue. - Dropping BM25 because "embeddings understand everything". They blur near-identical codes and IDs.
Quick recap
- BM25 matches exact words, and rare words count more.
- Dense search matches meaning, even when the words differ.
- RRF adds
1 / (60 + rank)from each list, so raw scores are never compared.
Hybrid search is the first pass. The next step, reranking, re-orders its top few with a slower model.
Try it yourself
Pass the dense list to rrf twice, as in rrf(bm25, dense, dense), and watch which articles move up on the code search. You've just given dense search double weight.
Related course on Udemy
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (paid course, opens in a new tab)Related posts
The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
Ingest, chunk, embed, store, retrieve, rerank and generate, in one Python file. Follow one question through a 26-chunk employee handbook to an answer that cites its source.
Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
Ask one question of a whole collection of vectors: which items are closest to this one? Normalise, score every row with one matrix multiply, keep the top k or everything above a threshold, and check it with NearestNeighbors.
Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
A smart model has never read your company's files, and they change every month. Three ways to give it the facts: paste everything, fine-tune, or retrieve only the right pieces. Follow a refund-policy question through all three and see why RAG wins when documents change.
Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
Swap a toy embedder for a model that learned. Two roads (all-MiniLM-L6-v2 on your machine, or OpenAI's API with your key), three sizes (384, 1,536 and 3,072 numbers), one rule, and three use cases built on the same rank function, with real scores.