Blog · Search Systems

Hybrid Search: BM25 + Vectors

BM25 finds exact words. Embeddings find meaning. Neither is enough on its own — hybrid search fuses both. A beginner-friendly guide to Reciprocal Rank Fusion, score fusion, and reranking, with Python code and a live demo.

🧩 Part 1 — Two Retrievers, Two Blind Spots

A search system has one job: given a query, return the documents that actually answer it. There are two fundamentally different ways to decide "relevant", and each one is blind to something the other sees.

🔤 BM25 — the literal librarian

Matches exact words. Brilliant at error codes, product SKUs, names, and rare jargon. Completely blind to synonyms — search "car" and it will never return a page about "automobiles".

🧠 Vectors — the well-read friend

Matches meaning. Understands that "car" and "automobile" are the same idea. But it can miss an exact identifier like E4021 because that token carries no learned meaning.

The failure modes, side by side

QueryBM25Vector search
"E4021 connection refused"Exact match found ✅May miss the code ❌
"how do I fix a broken database link"No shared words → nothing ❌Finds the E4021 doc ✅
"cheap flights"Misses "low-cost airfare" ❌Understands the intent ✅
"SKU-8842-BLK"Instant exact hit ✅Identifier is out-of-vocabulary ❌
The key insight: these blind spots are complementary. Where one retriever fails, the other usually succeeds. That is the entire motivation for hybrid search.

⚖️ Part 2 — The Fusion Problem

So we run both retrievers. Now we have two ranked lists. How do we merge them into one? This sounds trivial and is where most implementations go wrong.

The naive approach is to add the scores: final = bm25_score + cosine_sim. This is broken, because the two numbers live on completely different scales.

BM25 score
Unbounded. Can be 0.4, can be 18.7.
Range: 0 → ∞
Cosine similarity
Bounded between -1 and 1.
Range: -1 → 1

Add them directly and BM25 always wins by sheer magnitude. A document with a BM25 score of 18.7 and a cosine of 0.1 beats a document with BM25 0.4 and cosine 0.99 — even though the second is almost certainly the better answer. The fusion is dominated by whichever retriever happens to produce bigger numbers.

Two ways to fix it

  • ①
    Normalise the scores, then weight themSquash both score lists into a common range (min-max or z-score), then combine with weights: α·vector + (1-α)·bm25. Requires tuning α and is sensitive to outliers.
  • ②
    Ignore the scores entirely — use only ranksThis is Reciprocal Rank Fusion. Because it never looks at raw scores, the scale problem disappears completely. No normalisation, no tuning.
Rule of thumb: start with RRF. It is the default in Elasticsearch, Weaviate, Qdrant, and most RAG frameworks for exactly this reason.

📐 The RRF Formula (Plain English)

Reciprocal Rank Fusion
RRF(d) = Σ over each retriever r of: 1 / (k + rank_r(d)) Where: d — a document rank_r(d) — the position of d in retriever r's list (1 = best) k — damping constant, typically 60 Σ — sum the contributions from every retriever If a document does not appear in a retriever's list, it contributes 0.
Why it works. A document ranked #1 by one retriever earns 1/(60+1) ≈ 0.0164. Ranked #1 by both retrievers, it earns ≈ 0.0328 — double. A document ranked #1 by one and #50 by the other earns 0.0164 + 0.0018 ≈ 0.0182. So agreement between retrievers is rewarded, which is exactly the signal you want.

What the k constant does

k valueEffectWhen to use
k = 0Pure 1/rank — top result dominates heavilyRarely; very brittle
k = 60Balanced damping (the standard default)Almost always — start here
k = 100+Flattens differences between ranksWhen both retrievers are noisy

Worked example

Two retrievers, k = 60. Doc A is #1 in BM25 and #3 in vectors. Doc B is #2 in both.

Score calculation
Doc A: 1/(60+1) + 1/(60+3) = 0.01639 + 0.01587 = 0.03226 Doc B: 1/(60+2) + 1/(60+2) = 0.01613 + 0.01613 = 0.03226 → A tie. Both retrievers agreeing on Doc B is worth as much as Doc A's stronger single-retriever position.
This is the behaviour you want: consensus beats a single strong opinion. It is also why RRF is so robust out of the box.

🐍 Python Code — Build Hybrid Search

We build it in four steps: the lexical retriever, the dense retriever, the fusion step, and an alternative weighted fusion. Install the two libraries first.

Install once: pip install rank-bm25 sentence-transformers numpy · rank-bm25 · sentence-transformers

Step 1 — The lexical retriever (BM25)

python · lexical_retriever.py
# ── Retriever 1: BM25 (lexical / exact terms) ─────────────────
from rank_bm25 import BM25Okapi

documents = [
    "python developer roadmap guide",
    "vector database for semantic search",
    "bm25 keyword ranking in elasticsearch",
    "error code E4021 connection refused",
]

tokenized = ***REDACTED*** for d in documents]
bm25      = BM25Okapi(tokenized)

def bm25_search(query, top_k=50):
    scores = bm25.get_scores(query.lower().split())
    ranked = sorted(enumerate(scores), key=lambda x: x[1], reverse=True)
    return [(idx, score) for idx, score in ranked[:top_k]]

# Query: "E4021 connection error"
# BM25 finds the exact error code instantly ✅

Step 2 — The dense retriever (vectors)

python · dense_retriever.py
# ── Retriever 2: dense vectors (semantic / meaning) ───────────
from sentence_transformers import SentenceTransformer
import numpy as np

model = SentenceTransformer("all-MiniLM-L6-v2")

# Embed the corpus once, store the matrix
doc_vectors = model.encode(documents, normalize_embeddings=True)

def vector_search(query, top_k=50):
    q_vec = model.encode([query], normalize_embeddings=True)[0]
    # cosine similarity == dot product when vectors are normalised
    sims   = doc_vectors @ q_vec
    ranked = np.argsort(-sims)[:top_k]
    return [(int(i), float(sims[i])) for i in ranked]

# Query: "how do I fix a broken database link"
# Vector search finds the E4021 doc even with zero shared words ✅

Step 3 — Fuse with Reciprocal Rank Fusion

python · hybrid_rrf.py
# ── Fusion: Reciprocal Rank Fusion (RRF) ──────────────────────

def reciprocal_rank_fusion(ranked_lists, k=60):
    """
    ranked_lists: list of ranked lists, each a list of (doc_id, score)
                  sorted best-first. Scores are IGNORED — only rank matters.
    k:            damping constant (60 is the standard default)
    """
    fused = {}
    for ranked in ranked_lists:
        for position, (doc_id, _score) in enumerate(ranked):
            # position is 0-based, so rank = position + 1
            fused[doc_id] = fused.get(doc_id, 0.0) + 1.0 / (k + position + 1)
    return sorted(fused.items(), key=lambda x: x[1], reverse=True)


def hybrid_search(query, top_k=10):
    lexical  = bm25_search(query, top_k=50)
    semantic = vector_search(query, top_k=50)
    fused    = reciprocal_rank_fusion([lexical, semantic], k=60)
    return [(documents[i], score) for i, score in fused[:top_k]]


for rank, (doc, score) in enumerate(hybrid_search("E4021 connection error"), 1):
    print(f"{rank}. RRF={score:.5f}  →  {doc}")

Step 4 — Alternative: weighted score fusion

python · weighted_fusion.py
# ── Alternative: weighted score fusion (needs normalisation) ──

def min_max(scores):
    lo, hi = min(scores), max(scores)
    if hi == lo:
        return [0.0] * len(scores)
    return [(s - lo) / (hi - lo) for s in scores]


def weighted_fusion(query, alpha=0.5, top_k=10):
    """alpha=0 → pure BM25, alpha=1 → pure vectors."""
    lexical  = dict(bm25_search(query, top_k=50))
    semantic = dict(vector_search(query, top_k=50))

    candidates = set(lexical) | set(semantic)
    lex_norm = dict(zip(lexical, min_max(list(lexical.values()))))
    vec_norm = dict(zip(semantic, min_max(list(semantic.values()))))

    scored = []
    for doc_id in candidates:
        score = (alpha * vec_norm.get(doc_id, 0.0)
                 + (1 - alpha) * lex_norm.get(doc_id, 0.0))
        scored.append((doc_id, score))

    scored.sort(key=lambda x: x[1], reverse=True)
    return [(documents[i], s) for i, s in scored[:top_k]]


# Tune alpha on a labelled query set — do not guess it.
for alpha in [0.3, 0.5, 0.7]:
    print(f"alpha={alpha}", weighted_fusion("semantic search python", alpha)[:3])

🎮 Interactive Demo

Type a query, edit the corpus, and switch between BM25-only, vector-only, and hybrid RRF to see how the ranking changes. The vector retriever here uses a small hand-built concept space so it runs entirely in your browser — a real system would use a trained embedding model.

🎯 Part 3 — Reranking: The Third Stage

Hybrid search is a recall tool: it makes sure the right document is somewhere in the candidate set. Reranking is a precision tool: it puts the best document at the top. Production systems usually run both.

  • 1
    Retrieve (fast, cheap)BM25 + vectors, top 50 each. Milliseconds. Optimised for recall.
  • 2
    Fuse (instant)RRF merges the two lists into one candidate set of ~50-100 docs.
  • 3
    Rerank (slow, accurate)A cross-encoder reads each (query, document) pair jointly and scores true relevance. Keep the top 5-10 for the LLM.
Why a cross-encoder? Bi-encoders (the embedding model) encode query and document separately, so they cannot see interactions between them. A cross-encoder sees both at once and is far more accurate — but it costs a forward pass per candidate, which is why you only run it on the top ~20.
StageCostOptimisesTypical size
BM25 retrieveVery low ✅RecallTop 50
Vector retrieveLow ✅RecallTop 50
RRF fusionNegligible ✅Consensus~100
Cross-encoder rerankHigh ❌PrecisionTop 5-10

🚀 Production Notes

Things that bite you once you move past a toy example:

  • Keep the two indexes in sync. BM25 lives in Elasticsearch or Lucene; vectors live in Qdrant, pgvector, or FAISS. A document added to one but not the other silently degrades results. Index through a single pipeline.
  • Retrieve more than you need. Pulling top 50 from each retriever before fusing gives RRF room to find consensus. Fusing only top 10 throws away the signal.
  • Do not tune RRF's k blindly. k=60 is a well-tested default. Change it only against a labelled evaluation set, and measure nDCG or MRR.
  • Watch the embedding model's domain. A general-purpose model like all-MiniLM-L6-v2 will underperform on legal, medical, or code corpora. This is precisely where BM25 saves you.
  • Chunking matters more than fusion. If your chunks are 2000 tokens of mixed topics, no fusion strategy will rescue retrieval quality. Chunk on semantic boundaries first.
Common mistake: adding scores from two retrievers without normalising. If you see BM25 dominating every fused result, this is why. Switch to RRF or normalise first.

Where hybrid search is built in

Elasticsearch OpenSearch Weaviate Qdrant Azure AI Search — all ship RRF-based hybrid retrieval as a first-class feature. You rarely need to implement fusion by hand in production.

🧭 Where This Fits

Comments

Ask questions, share feedback, or reply to other readers. Sign in with Google to join the discussion.

Sign in with Google to add comments and replies.

Loading comments...