Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

Learning path · 12 steps

Build and Measure a RAG System
  1. 1
    What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  2. 2
    Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  3. 3
    Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  4. 4
    Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  5. 5
    Vector Databases Hands-On: The Same Search in Chroma and pgvector
  6. 6
    Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  7. 7
    The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  8. 8
    RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  9. 9
    Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  10. 10
    Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  11. 11
    Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  12. 12
    RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Retrieval and RAG

Learning path: Build and Measure a RAG System · Step 9 of 12

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.

Chaand Sheikh

·27 November 2026Retrieval and RAG

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 wordIn how many articlesWeight
error4 of 120.64 (common, small)
e-40721 of 122.04 (rare, about three times bigger)
refused0 of 120 (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.

How RRF puts A05 above A06 my card was refused BM25 rank Dense rank RRF score A05 Why a payment is declined 2 → 1/62 1 → 1/61 0.0325 (first) A06 Redeem a gift card 1 → 1/61 4 → 1/64 0.0320 (second) An article both lists rank high collects the most points, like the two detectives.
Values from the run: the ranks, the 1 / (60 + rank) points and the fused scores.

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:

QueryRight articleBM25DenseHybrid
error E-4072A01yesnoyes
my card was refusedA05noyesyes
reset my passwordA07yes (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-4072 must 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in the learning path Build and Measure a RAG System · step 9 of 12

Previous
RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
Next post
Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't

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

What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break

A customer types "I cannot log in" and keyword search finds nothing, although a password-reset article exists. Turn meaning into numbers by hand, find the nearest point with math.dist, build a three-topic toy embedder that finds the right article at 1.00, and watch it score 0.00 on "I can't get into my account".

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.

On this page

  • Trust who both rank high
  • One help centre, two kinds of searcher
  • BM25: count words, rare words count more
  • Both searches in code
  • Each method fails once
  • Why not add the scores?
  • Reciprocal Rank Fusion
  • Hybrid gets all three
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.