Thursday, November 12, 2026

Source: Image created by Generative AI Lab using image generation models.

Hybrid Search for RAG: Combining BM25 and Vector Search

TL;DR

Keyword search finds the exact error code, vector search finds the user whose charts take forever, and hybrid search runs both and merges the results. This guide explains Reciprocal Rank Fusion, gives runnable Python, and reports a small test where RRF ranked best and a 50/50 score blend did worse than either search alone. Splitting the difference, it turns out, is not always diplomatic.

Three results worth a look:

Say a team builds a support assistant on top of its help center. One user pastes an error code, ERR_4031, and expects the page about that exact error. Another writes “my charts take forever to load” and expects the page about slow dashboards, which never uses the word “forever”. A retrieval step tuned for one kind of question tends to miss the other.

Hybrid search runs a keyword search (usually BM25) and a vector search side by side, then merges the two ranked lists into one. A widely used way to merge them is Reciprocal Rank Fusion (RRF), which adds up 1 / (60 + rank) for each document across the lists. In the small test in this guide, RRF gave the best mean reciprocal rank of the four methods we tried, while a 50/50 weighted blend of scores did worse than either search alone. This guide explains how each piece works, gives runnable Python code, and shows what our numbers can and cannot tell you.

Key Takeaways

  • Keyword search (BM25) is strong on exact terms: error codes, product names, parameter names. Vector search is meant for meaning, when the user’s words differ from the document’s.
  • Hybrid search runs both and fuses the results. Reciprocal Rank Fusion only uses ranks, so it needs no score scaling and has one setting, k, usually 60.
  • In our test on 30 help center articles and 20 labeled queries, RRF reached an MRR@10 of 0.774, against 0.749 for BM25 alone and 0.744 for the dense retriever alone. Recall@3 was 0.850 for BM25 and both hybrids.
  • Weighted score fusion with equal weights scored lower (MRR@10 0.715) than either retriever on its own. Score blending needs tuning on your own queries.
  • Fusion cannot find what neither retriever finds. Three paraphrased queries failed for every method, which points to the dense model, not the fusion step, as the next thing to improve.

Hybrid search is a retrieval method that combines a lexical retriever and a semantic retriever and returns one merged ranking. In a retrieval-augmented generation (RAG) system, that merged ranking decides which passages go into the language model’s prompt, so it decides what the model can answer from.

Three terms come up throughout this guide:

  • BM25 is a ranking function that scores a document by how often the query’s words appear in it, how rare those words are across the collection, and how long the document is. It matches words, not meaning.
  • Dense retrieval turns the query and each document into vectors (embeddings) and ranks documents by how close their vectors are to the query’s, usually by cosine similarity. Two texts can be close without sharing a word.
  • Fusion is the rule that merges the two rankings. The two common rules are Reciprocal Rank Fusion, which uses ranks, and weighted score fusion, which blends normalized scores.

Why Keyword and Vector Search Miss Different Things

Keyword search fails when the user and the document use different words. A user who asks “how do I get my money back” is looking for the refund policy, but the question shares no word with that page. BM25 has nothing to match on.

Vector search fails in the opposite direction. An embedding of “ERR_4031” carries little meaning on its own, and an embedding model may place it near any page that talks about errors or API keys. When the exact string matters, a model that blurs strings into meaning can rank the right page below several similar ones.

Because the two fail on different queries, a system that runs both has two chances to put the right document near the top. That is the whole argument for hybrid search. Whether it pays off depends on how often your users ask each kind of question, which is why the test later in this guide matters more than the theory.

How Reciprocal Rank Fusion Works

Reciprocal Rank Fusion was introduced by Gordon Cormack, Charles Clarke and Stefan Buettcher in “Reciprocal Rank Fusion Outperforms Condorcet and Individual Rank Learning Methods” (SIGIR 2009). For every document, it adds up one small number per ranked list:

RRF(d) = sum over lists of 1 / (k + rank of d in that list)

The constant k dampens the effect of the very top ranks. The paper used k = 60, and 60 is a common default in libraries and search engines. A worked example: a document ranked 1st by BM25 and 3rd by vector search scores 1/61 + 1/63, about 0.0323. A document ranked 2nd by both scores 1/62 + 1/62, also about 0.0323. Agreement between the lists counts about as much as one list being sure.

RRF has two practical advantages. It ignores raw scores, so it does not matter that BM25 scores can be 0 to 20 while cosine similarities sit between -1 and 1. And with only one setting, it is hard to overfit to a small test set.

Weighted Score Fusion and Why Scaling Matters

The alternative is to blend scores directly: final score = alpha × dense score + (1 – alpha) × BM25 score. Before blending, both scores must be put on the same scale, commonly with min-max scaling per query (the best document gets 1, the worst gets 0).

Weighted fusion can beat RRF when one retriever is clearly better for your data, because you can lean on it. The cost is a setting to tune, and scores that can be fragile: one very high BM25 score on a long document can push every other score toward zero after scaling. In our test, equal weights (alpha = 0.5) gave the lowest MRR of all four methods.

A Runnable Hybrid Search in Python

The script below builds a small help center for a made-up analytics product (30 short articles written for this test) and 20 questions with the articles that answer them. It runs BM25 with rank_bm25, a dense retriever, both fusion methods, and an evaluation.

One honest note on the dense retriever. Our test machine could not download models from Hugging Face, so the dense side uses latent semantic analysis (LSA): TF-IDF vectors reduced to 24 dimensions with scikit-learn’s TruncatedSVD. LSA is a real dense method, but it learns word relations only from these 30 articles, so it is much weaker on paraphrases than a neural embedding model. To use one, replace the embed function and doc_vecs with a model such as all-MiniLM-L6-v2 from sentence-transformers; everything else stays the same.

Install the three packages (we ran Python 3.13 with numpy 2.5.4, scikit-learn 1.9.1 and rank-bm25 0.2.2):

pip install rank-bm25 scikit-learn numpy

Then run this script:

import re
import numpy as np
from rank_bm25 import BM25Okapi
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.preprocessing import normalize

# A help center for a made-up analytics product, written for this test.
DOCS = {
    "d01": "Reset your password: open the sign in page, choose Forgot password, and follow the link we email you. The link expires after 30 minutes.",
    "d02": "Single sign-on with SAML: admins upload the identity provider metadata XML, map the email attribute, and test the login before enforcing SSO for everyone.",
    "d03": "Error ERR_4031 means the API key has no permission for the project. Create a key with the analytics:read scope or ask an admin to grant it.",
    "d04": "Error ERR_5002 appears when an export takes longer than 10 minutes. Narrow the date range or schedule the export to run overnight.",
    "d05": "Two-factor authentication: turn on 2FA in Security settings and scan the QR code with an authenticator app. Recovery codes let you log in if you lose your phone.",
    "d06": "Locked out of your account after too many failed log in attempts? Wait 15 minutes or ask an admin to unlock the user from the Members page.",
    "d07": "Invite teammates from the Members page. Each invite email is valid for 7 days and can be resent at any time.",
    "d08": "Roles and permissions: Viewers can read dashboards, Editors can change them, and Admins manage billing, members and SSO.",
    "d09": "Billing and invoices: download past invoices as PDF from the Billing page. Invoices are issued on the first day of each month.",
    "d10": "Change your plan or cancel your subscription from the Billing page. Downgrades take effect at the end of the current billing period.",
    "d11": "Refund policy: annual plans can be refunded within 14 days of purchase. Monthly plans are not refunded, but you can cancel any time.",
    "d12": "Connect a PostgreSQL database: enter the host, port, database name and a read-only user. Allow our IP addresses in your firewall.",
    "d13": "Connect Snowflake with key pair authentication. Paste the private key, the account identifier and the warehouse name in the connection form.",
    "d14": "Sync schedules: data sources refresh every hour by default. Enterprise plans can refresh every 5 minutes.",
    "d15": "Slow dashboards usually come from charts that scan large tables. Add a date filter, pre-aggregate in the warehouse, or enable query caching.",
    "d16": "Query caching stores chart results for 15 minutes, so repeated views of a dashboard load faster and cost less warehouse compute.",
    "d17": "Export a dashboard to CSV or PDF from the Share menu. Large exports run in the background and arrive by email.",
    "d18": "Embed a dashboard in your own app with a signed URL. The signature expires, so generate a new URL on each page load.",
    "d19": "Webhooks send a POST request to your endpoint when an alert fires. Verify the X-Signature header with your webhook secret.",
    "d20": "Alerts: set a threshold on any metric and get notified by email, Slack or webhook when the value crosses it.",
    "d21": "Rate limits: the REST API allows 600 requests per minute per key. Responses include headers that show how many requests remain.",
    "d22": "API pagination uses a cursor. Pass the next_cursor value from one response to get the following page of results.",
    "d23": "Data retention: raw events are kept for 13 months on the Pro plan and 25 months on Enterprise. Aggregates are kept as long as the account exists.",
    "d24": "Delete your account from Settings. All dashboards, data sources and members are removed after 30 days, and this cannot be undone.",
    "d25": "GDPR requests: to export or erase the personal data of one end user, send their user ID to the privacy API endpoint.",
    "d26": "Audit log: Admins on Enterprise can see who changed dashboards, permissions and data sources, with time and IP address.",
    "d27": "Time zones: each dashboard uses the workspace time zone unless a viewer picks another one in their profile.",
    "d28": "Calculated fields let you build new metrics from existing columns with formulas such as ratios, running totals and moving averages.",
    "d29": "Dashboard filters apply to every chart on the page. Pin a filter to keep it when you share the dashboard link.",
    "d30": "Mobile app: view dashboards and receive alerts on iOS and Android. Editing dashboards is only available on the web.",
}

# Questions a user might type, with the articles that answer them.
QUERIES = [
    ("ERR_4031", {"d03"}),
    ("ERR_5002 export failed", {"d04"}),
    ("SAML metadata XML upload", {"d02"}),
    ("next_cursor pagination", {"d22"}),
    ("X-Signature header webhook", {"d19"}),
    ("I forgot my login credentials", {"d01"}),
    ("can't get into my account after typing the wrong password several times", {"d06"}),
    ("how do I get my money back", {"d11"}),
    ("my charts take forever to load", {"d15", "d16"}),
    ("stop paying for the product", {"d10"}),
    ("add a colleague to the workspace", {"d07"}),
    ("lost my phone with the authenticator", {"d05"}),
    ("how long do you keep my data", {"d23"}),
    ("remove a customer's personal information", {"d25"}),
    ("who changed this dashboard", {"d26"}),
    ("put a dashboard inside our website", {"d18"}),
    ("too many requests error from the API", {"d21"}),
    ("Snowflake private key connection", {"d13"}),
    ("refresh data every 5 minutes", {"d14"}),
    ("get notified in Slack when revenue drops", {"d20"}),
]

TOKEN = re.compile(r"[a-z0-9_]+")

def tokenize(text):
    return TOKEN.findall(text.lower())

ids = list(DOCS)
texts = [DOCS[i] for i in ids]

# Keyword retriever: BM25.
bm25 = BM25Okapi([tokenize(t) for t in texts])

def bm25_scores(query):
    return np.asarray(bm25.get_scores(tokenize(query)))

# Dense retriever: TF-IDF + truncated SVD (LSA), cosine similarity.
# Stands in for a neural embedding model: to swap one in, replace embed() and doc_vecs.
tfidf = TfidfVectorizer(token_pattern=r"[a-z0-9_]+", sublinear_tf=True)
svd = TruncatedSVD(n_components=24, random_state=42)
doc_vecs = normalize(svd.fit_transform(tfidf.fit_transform(texts)))

def embed(text):
    return normalize(svd.transform(tfidf.transform([text])))[0]

def dense_scores(query):
    return doc_vecs @ embed(query)

def ranking(scores):
    return [ids[i] for i in np.argsort(-scores, kind="stable")]

def rrf(rankings, k=60):
    """Reciprocal Rank Fusion: sum of 1 / (k + rank) over the lists."""
    fused = {}
    for r in rankings:
        for rank, doc in enumerate(r, start=1):
            fused[doc] = fused.get(doc, 0.0) + 1.0 / (k + rank)
    return sorted(fused, key=lambda d: (-fused[d], ids.index(d)))

def minmax(x):
    lo, hi = x.min(), x.max()
    return (x - lo) / (hi - lo) if hi > lo else np.zeros_like(x)

def weighted(query, alpha=0.5):
    """Weighted score fusion: alpha * dense + (1 - alpha) * BM25, after min-max scaling."""
    return ranking(alpha * minmax(dense_scores(query)) + (1 - alpha) * minmax(bm25_scores(query)))

def evaluate(search, k=3):
    recall, mrr = [], []
    for q, rel in QUERIES:
        r = search(q)
        recall.append(len(set(r[:k]) & rel) / len(rel))
        first = next((i for i, d in enumerate(r[:10], start=1) if d in rel), None)
        mrr.append(1.0 / first if first else 0.0)
    return np.mean(recall), np.mean(mrr)

METHODS = {
    "BM25 only": lambda q: ranking(bm25_scores(q)),
    "Dense only": lambda q: ranking(dense_scores(q)),
    "Hybrid (RRF, k=60)": lambda q: rrf([ranking(bm25_scores(q)), ranking(dense_scores(q))]),
    "Hybrid (weighted, alpha=0.5)": lambda q: weighted(q, 0.5),
}

print(f"{'Method':32} {'Recall@3':>9} {'MRR@10':>8}")
for name, search in METHODS.items():
    r, m = evaluate(search)
    print(f"{name:32} {r:9.3f} {m:8.3f}")

for a in (0.0, 0.25, 0.5, 0.75, 1.0):
    r, m = evaluate(lambda q: weighted(q, a))
    print(f"alpha={a:.2f}  recall@3={r:.3f}  MRR@10={m:.3f}")

Recall@3 is the share of each query’s relevant articles that appear in the top three results, averaged over the queries. MRR@10 (mean reciprocal rank) averages 1 divided by the position of the first relevant result, counting 0 when none appears in the top ten. Recall tells you whether the right passage made it into a short prompt; MRR tells you how high it ranked.

What the Test Showed

These are the numbers the script printed:

Method Recall@3 MRR@10
BM25 only 0.850 0.749
Dense only (LSA) 0.800 0.744
Hybrid, Reciprocal Rank Fusion (k = 60) 0.850 0.774
Hybrid, weighted fusion (alpha = 0.5) 0.850 0.715

RRF ranked the right article highest on average. It matched BM25 on recall and moved the first relevant result up on a few queries: “my charts take forever to load” (BM25 had it 2nd, RRF 1st) and “put a dashboard inside our website” (BM25 3rd, RRF 2nd). On the exact-term queries, such as ERR_4031, next_cursor and X-Signature, all methods found the right article first.

The weighted blend shows why tuning matters. With alpha from 0 to 1 in steps of 0.25, MRR@10 went 0.749, 0.740, 0.715, 0.735 and 0.744. The middle setting, which looks like the safe choice, was the worst one here.

The most useful result is the failures. Three queries had no relevant article in the top three for any method: “how do I get my money back” (refund policy at rank 14 for BM25 and dense, 11 for RRF), “stop paying for the product” (rank 7 or 8) and “add a colleague to the workspace” (rank 19 to 21). All three are paraphrases with no shared words. The word “colleague” appears in none of the 30 articles, so LSA, which learns word relations only from those articles, has no way to connect it to “teammates”. Fusion cannot rescue a document that both lists rank low. That is the job of a stronger embedding model.

What This Test Can and Cannot Tell You

Twenty queries are enough to show how the methods behave, not to rank them with confidence. A difference of 0.025 in MRR is one or two queries moving by a rank. Treat the table as a worked example of the method, not as a benchmark.

The result that does generalize is the shape of the evaluation. Write down 50 to 200 real questions from your users, label the passages that answer them, and run the same four methods. If most of your traffic is error codes and product names, BM25 may carry the load and hybrid adds little. If most of it is people describing problems in their own words, the dense side and its model matter most, and hybrid protects the exact-term queries.

Using Hybrid Search in a RAG Pipeline

In a production RAG system, hybrid search usually sits in this order:

  1. Retrieve a larger set from each side, for example the top 20 to 50 from BM25 and the top 20 to 50 from the vector index.
  2. Fuse them with RRF into one list.
  3. Optionally rerank the top of that list with a cross-encoder or a reranking model, which reads the query and each passage together.
  4. Send only the top few passages to the language model.

Step 4 is where retrieval quality turns into cost. Every passage you add is input tokens on every request, so a retriever that puts the right passage in the top three lets you send three passages instead of ten. Our guide to using fewer LLM tokens covers the cost side, and the guide to BM25S for fast BM25 retrieval in Python covers the keyword side at a larger scale than rank_bm25 handles comfortably.

Retrieval is one component among several. If the assistant also calls tools or takes actions, see implementing AI agents in Python, and for how retrieval, models and tools fit into one product, what compound AI systems are.

  • Collect real user questions and label the passages that answer them before changing anything.
  • Measure BM25 alone and vector search alone first, so you know what hybrid has to beat.
  • Start with RRF at k = 60. Try weighted fusion only if one side is clearly stronger, and tune alpha on held-out queries.
  • Read the queries every method fails. If they are paraphrases, improve the embedding model; if they are exact terms, check tokenization (codes with underscores or dots are often split).
  • Keep the evaluation script and rerun it whenever you change the model, the chunking or the documents.

Back to the Help Center

The support assistant from the opening needed to handle both the user with ERR_4031 and the user whose charts “take forever”. In our version of that help center, BM25 already found the error code, and fusing it with a dense retriever moved the slow dashboard page to the top. The refund question exposed the real gap: no fusion rule finds a page that neither retriever understands. Hybrid search is the safe default, and a labeled set of real questions is what tells you which half to improve next.

Frequently Asked Questions

What Value of k Should I Use for Reciprocal Rank Fusion?

Start with 60, the value used in the original RRF paper and a common default in search tools. A smaller k gives more weight to the very top of each list; a larger k flattens the differences between ranks. Change it only if an evaluation on your own queries shows a clear gain.

Is Reciprocal Rank Fusion Better Than Weighted Score Fusion?

Not always. RRF needs no score scaling and has one setting, which makes it a strong default. Weighted fusion can do better when one retriever is clearly stronger on your data, but it needs a tuned weight, and in our test the untuned 50/50 blend scored below both single retrievers.

No. For a few thousand passages, the in-memory approach in this guide works. At larger scale you need an index for each side, and several search engines and vector databases offer hybrid search with RRF built in, so check what your current stack supports before adding another system.

Does Hybrid Search Replace a Reranker?

No, they do different jobs. Hybrid search widens the set of candidates by combining two ways of finding them. A reranker reorders a short list by reading each passage together with the query. Many RAG systems use both: hybrid retrieval first, then a reranker on the top results.

How Many Test Queries Do I Need?

Enough that one query moving a rank does not change your conclusion. Twenty, as in this guide, shows how the methods behave. For a decision about a production system, aim for 50 to 200 real questions, and include both exact-term queries and questions written in users’ own words.

Disclaimer: The content on this website reflects the views of contributing authors and not necessarily those of Generative AI Lab. This site may contain sponsored content, affiliate links, and material created with generative AI. Thank you for your support.

Generative AI Lab mascot
Generative AI Lab Editorial Team
Articles researched, written and edited by the Generative AI Lab team. About Generative AI Lab

Must read

- Advertisement -spot_img

More articles

- Advertisement -spot_img

Latest articles