A user types “ERR_4021” into your support bot. The bot returns three articles about general error handling and nothing about error 4021. The article exists. It is sitting in your index. Vector search just could not find it, because to an embedding model “ERR_4021” and “ERR_4022” are nearly the same point in space, and neither is close to “database connection timeout,” which is what the article is actually about.

This is the failure mode nobody warns you about when you build your first RAG system. Vector search is sold as the thing that replaced keyword search, so you delete keyword search. Then you ship, and the complaints come in: the bot cannot find a part number, cannot find a function name, cannot find a person’s name, cannot match an exact phrase a user copy-pasted from a document. Every one of those is a query that BM25 would have nailed in 2009.

The fix is not better embeddings. It is to stop choosing. Run both retrievers and fuse the results. On real knowledge bases this consistently buys 15 to 30 percent on retrieval accuracy over pure vector search, and it is maybe forty lines of code. This post walks through why vector search fails on exact matches, how reciprocal rank fusion combines two ranked lists without needing to compare incomparable scores, how to wire it up in both LlamaIndex and LangChain, and when to lean keyword versus semantic.

The Naive System: Embed Everything, Search by Cosine

Here is the RAG retrieval everyone builds first. Chunk the docs, embed each chunk, store the vectors, and at query time embed the question and pull the nearest neighbors.

from openai import OpenAI
import numpy as np

client = OpenAI()

def embed(text: str) -> np.ndarray:
    r = client.embeddings.create(model="text-embedding-3-small", input=text)
    return np.array(r.data[0].embedding)

# Index time
chunks = load_and_chunk(corpus)
vectors = np.stack([embed(c.text) for c in chunks])

# Query time
def retrieve(query: str, k: int = 5):
    q = embed(query)
    scores = vectors @ q / (np.linalg.norm(vectors, axis=1) * np.linalg.norm(q))
    top = np.argsort(scores)[::-1][:k]
    return [chunks[i] for i in top]

For questions phrased in natural language this is genuinely good. Ask “how do I reset my password” and it will find the chunk titled “Account Recovery Procedure” even though the words barely overlap. That is the whole point of embeddings: they match meaning, not tokens. This is why vector search felt like magic the first time you used it.

The trouble is that a meaning-based matcher is the wrong tool whenever the query is not really about meaning.

Where It Breaks: Identifiers Have No Semantics

Embedding models are trained to map similar meanings to nearby vectors. That objective actively works against you for a whole category of tokens that carry identity rather than meaning:

  • Acronyms and codes. “ERR_4021,” “SKU-99B,” “CVE-2026-1337.” The model has little signal to separate these from their siblings. One digit of difference is a completely different document to a human and nearly the same vector to the model.
  • Proper nouns. Product names, people, internal service names. “Did Project Kestrel ship?” The embedding for “Kestrel” is dominated by the bird, not your internal project.
  • Exact phrases. A user copies an error string or a sentence from a contract and pastes it in. They want the document containing that exact string. Vector search returns things that are “about” the topic instead.
  • Rare and out-of-vocabulary terms. Anything the embedding model saw rarely in training lands in a poorly-shaped region of the space.

The uncomfortable part is that these failures are silent. The system returns five results with high confidence scores. Nothing errors. The right document was simply ranked eighth and never made the cutoff. You only find out when a user tells you, and most users do not tell you, they just stop trusting the bot.

Meanwhile a dumb lexical scorer solves all of this for free. BM25 ranks documents by term overlap, weighted so that rare terms count more and long documents do not get an unfair advantage. “ERR_4021” is a rare term. The one document containing it rockets to the top. BM25 does not know what 4021 means and does not need to.

from rank_bm25 import BM25Okapi

tokenized = [c.text.lower().split() for c in chunks]
bm25 = BM25Okapi(tokenized)

def retrieve_bm25(query: str, k: int = 5):
    scores = bm25.get_scores(query.lower().split())
    top = np.argsort(scores)[::-1][:k]
    return [chunks[i] for i in top]

So now you have two retrievers with complementary blind spots. Vector search owns paraphrase and concept matching. BM25 owns exact terms and identifiers. The obvious move is to use both. The non-obvious part is how to combine them.

Why You Cannot Just Add the Scores

The naive combination is to normalize both score sets and add them with a weight:

final = alpha * normalize(vector_scores) + (1 - alpha) * normalize(bm25_scores)

This looks reasonable and it is a trap. Cosine similarity lives on a bounded, roughly comparable scale across queries. BM25 does not: its scores are unbounded and their magnitude depends on corpus statistics, query length, and how rare the matched terms are. A query with one very rare term produces a huge BM25 score; a query with common terms produces a small one. Min-max normalizing per query makes the numbers look comparable while quietly distorting them, and the single best keyword hit can get flattened to the same range as a mediocre one. You end up hand-tuning alpha per query type, which is exactly the fragile mess you were trying to avoid.

The scores are not measuring the same thing, so do not try to average them. Average the ranks instead.

Reciprocal Rank Fusion

Reciprocal rank fusion (RRF) throws the scores away and keeps only the position each document landed in within each ranked list. A document’s fused score is the sum, across retrievers, of one over its rank plus a constant:

RRF(d) = sum over retrievers r of  1 / (k + rank_r(d))

rank_r(d) is the 1-based position of document d in retriever r’s list. k is a smoothing constant, conventionally 60. That constant does two things: it dampens the influence of the very top ranks so a single first-place finish cannot completely dominate, and it gracefully handles documents that appear in one list but not the other.

The elegance is that rank is unit-free. First place in BM25 and first place in vector search are directly comparable even though a BM25 score of 14.2 and a cosine score of 0.81 are not. A document that both retrievers rank highly floats to the top. A document that one retriever loves and the other has never heard of still gets a fair contribution from the list that ranked it.

def reciprocal_rank_fusion(result_lists, k: int = 60, top_n: int = 5):
    scores = {}
    docs = {}
    for results in result_lists:
        for rank, doc in enumerate(results, start=1):
            scores[doc.id] = scores.get(doc.id, 0.0) + 1.0 / (k + rank)
            docs[doc.id] = doc
    ranked = sorted(scores.items(), key=lambda x: x[1], reverse=True)
    return [docs[doc_id] for doc_id, _ in ranked[:top_n]]

hybrid = reciprocal_rank_fusion([
    retrieve(query, k=20),        # dense / vector
    retrieve_bm25(query, k=20),   # sparse / lexical
])

Two practical notes. First, pull a wider candidate set from each retriever than you ultimately want (20 in, 5 out is a sane default) so RRF has room to work. Second, you can weight a retriever by multiplying its contribution:

scores[doc.id] += weight_r * (1.0 / (k + rank))

That weight is the one knob worth tuning, and it is far more stable than tuning raw score blends because you are scaling a bounded quantity.

Here is the whole data flow end to end:

                       query
                         |
          +--------------+--------------+
          |                             |
    embed query                   tokenize query
          |                             |
   dense retriever               sparse retriever
   (vector / ANN)                   (BM25)
          |                             |
   ranked list A                 ranked list B
   [d3, d7, d1, ...]             [d9, d3, d2, ...]
          |                             |
          +--------------+--------------+
                         |
            reciprocal rank fusion (k=60)
                         |
                  fused top-N chunks
                         |
                  (optional reranker)
                         |
                   LLM generation

Doing It in LlamaIndex

LlamaIndex ships this as a first-class retriever. You build a vector retriever and a BM25 retriever over the same nodes, then hand both to QueryFusionRetriever with RRF as the fusion mode.

from llama_index.core import VectorStoreIndex
from llama_index.retrievers.bm25 import BM25Retriever
from llama_index.core.retrievers import QueryFusionRetriever

index = VectorStoreIndex(nodes)
vector_retriever = index.as_retriever(similarity_top_k=20)

bm25_retriever = BM25Retriever.from_defaults(
    nodes=nodes,
    similarity_top_k=20,
)

hybrid = QueryFusionRetriever(
    [vector_retriever, bm25_retriever],
    retriever_weights=[0.6, 0.4],   # lean semantic, keep keyword real
    similarity_top_k=5,
    mode="reciprocal_rerank",       # this is RRF
    num_queries=1,                  # set >1 to also fuse query rewrites
    use_async=True,
)

results = hybrid.retrieve("what causes ERR_4021 on login")

Two things worth knowing. mode="reciprocal_rerank" is RRF under the hood. And num_queries controls query expansion: set it above 1 and LlamaIndex generates paraphrases of the query, retrieves for each, and fuses all of them together, which helps recall at the cost of latency and tokens. Start at 1, measure, then decide.

Doing It in LangChain

LangChain expresses hybrid search through EnsembleRetriever, which also fuses with RRF. You give it the component retrievers and relative weights.

from langchain_community.retrievers import BM25Retriever
from langchain_community.vectorstores import FAISS
from langchain_openai import OpenAIEmbeddings
from langchain.retrievers import EnsembleRetriever

vectorstore = FAISS.from_documents(docs, OpenAIEmbeddings())
vector_retriever = vectorstore.as_retriever(search_kwargs={"k": 20})

bm25_retriever = BM25Retriever.from_documents(docs)
bm25_retriever.k = 20

hybrid = EnsembleRetriever(
    retrievers=[vector_retriever, bm25_retriever],
    weights=[0.6, 0.4],
)

results = hybrid.invoke("what causes ERR_4021 on login")

EnsembleRetriever applies weighted RRF with the same k=60 convention. The weights list is your keyword-versus-semantic dial. Note one operational difference from LlamaIndex: the in-memory BM25Retriever here rebuilds its index from the document list, so for large corpora you will want the BM25 side backed by a real search engine (Elasticsearch, OpenSearch, or a vector store with native sparse support like Qdrant or Weaviate) rather than held in process.

When to Weight Keyword vs Semantic

The weights are not a set-and-forget value. They depend on what your users actually type. Here is how I reason about it.

Query profileLeanWhy
Error codes, SKUs, API names, legal clausesKeyword (0.6 to 0.7 BM25)Identity matters more than meaning; exact tokens are the signal
Conversational questions, “how do I”, “why does”Semantic (0.6 to 0.7 vector)Paraphrase and synonym matching dominate
Mixed knowledge base (most real products)Balanced (0.5 / 0.5) startThen adjust from eval data, not vibes
Code search, log search, config lookupKeyword-heavyCode is mostly exact identifiers and rare tokens
Short queries (1 to 2 words)Nudge keywordToo little text for embeddings to disambiguate

The honest way to set these is not a table, it is an evaluation set. Collect 50 to 100 real queries, label the chunk that should be retrieved for each, and measure recall at k and mean reciprocal rank as you sweep the weight. You will usually find a broad plateau rather than a sharp peak, which is good news: it means the exact number does not matter much and you just need to be in the right region. If you cannot build an eval set yet, start at 0.5/0.5, because balanced hybrid beats pure vector on nearly every corpus I have measured.

One more lever worth mentioning: put a cross-encoder reranker after fusion. RRF gets the right documents into the top 20; a reranker like bge-reranker or Cohere Rerank reorders that short list using full query-document attention and reliably adds a few more points of precision. Fusion first, rerank second, generate third.

What Actually Works, and What to Skip

What works: adding BM25 to an existing vector pipeline is the highest return-on-effort change available to most RAG systems in 2026. It is cheap, it is well-supported in every major framework, and it fixes an entire class of embarrassing exact-match misses that no amount of embedding-model shopping will fix. If you only do one thing after reading this, add a BM25 retriever and fuse with RRF at default weights.

What is overrated: obsessing over the fusion constant k. Sixty is fine. I have never seen tuning it move a metric meaningfully. Spend that time on your eval set instead. Also overrated is per-query dynamic weighting with a classifier that decides keyword-vs-semantic on the fly; it sounds smart and in practice adds latency and a new failure mode for a gain that static balanced weights mostly already capture. Prove you need it before you build it.

What does not work: skipping measurement. Hybrid retrieval is easy to turn on and easy to misconfigure, and because the failures are silent you will not notice a bad weight from eyeballing a few queries. Build the small eval set. Thirty labeled queries is enough to catch a retriever that is quietly broken, and it is the difference between “we added hybrid search” and “we added hybrid search and it actually helped.”

The one-line version: vector search answers “what is this about,” keyword search answers “where is this exact thing,” real users ask both kinds of question in the same session, and reciprocal rank fusion lets you serve both without pretending their scores are the same currency.