Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Retrieval (RAG)AI guideIntermediate#rag#retrieval#search#bm25
Frame · ai-engineering / rag / 06-hybrid-search-bm25-and-vectors.mdGuide 018 / 103

Hybrid search with BM25 and vectors

Vector search understands that "get my money back" means "refund". Keyword search understands that "ERR-4012" means exactly ERR-4012 and nothing else. Real queries need both, which is why almost every mature RAG system ends up running a lexical retriever and a dense retriever side by side and merging the results. This doc covers how the two differ, how fusion works, and how to wire it up.

Why it matters

Dense embeddings are trained to capture meaning, and they are good at paraphrase, synonyms and fuzzy questions. They are weak at things that look like noise to a language model: product codes, version numbers, rare surnames, legal citations, error strings, and newly coined internal jargon the model never saw. BM25, the classic term-weighting function behind search engines like Lucene, does the opposite: it rewards exact term overlap, weighted by how rare the term is, and knows nothing about synonyms.

Their failure modes are largely complementary, so combining them raises recall without much downside. Anthropic's contextual retrieval write-up is a good public example: in their experiments, adding BM25 on top of contextual embeddings further reduced the top-20 retrieval failure rate compared with embeddings alone.

How it works

You run two retrievers against the same chunk collection, each returning a ranked list, then fuse the lists into one.

BM25 scores a chunk for a query by summing, over each query term, the term's inverse document frequency times a saturating function of how often it appears in the chunk, normalized by chunk length. Two parameters (k1 for term-frequency saturation, b for length normalization) are usually left at library defaults.

Learned sparse models (SPLADE-style, or the sparse output of BGE-M3) are an alternative to BM25: they produce sparse term-weight vectors that include expansion terms, which helps with vocabulary mismatch while keeping exact matching.

Fusion is where people get stuck, because BM25 scores and cosine similarities live on completely different scales. There are two common approaches:

  • Reciprocal rank fusion (RRF). Ignore scores and use ranks. Each document gets the sum over lists of 1 / (k + rank). In the original paper by Cormack, Clarke and Büttcher (SIGIR 2009), k = 60 was fixed in a pilot study and the method almost always improved on the best individual ranking. It needs no tuning and is robust, which is why it is the default in many engines.
  • Weighted score fusion. Normalize each list's scores (for example min-max to 0 to 1) and combine with a weight. Weaviate's relativeScoreFusion (the default since v1.24) does this, with an alpha parameter where 0 is pure keyword and 1 is pure vector. This can outperform RRF when tuned, but the weight is another hyperparameter to evaluate.
Rendering diagram…

A worked RRF example: a chunk ranked 1st by BM25 and 5th by vectors scores 1/61 + 1/65, about 0.0318. A chunk ranked 2nd by vectors and absent from BM25 scores 1/62, about 0.0161. Agreement between retrievers is rewarded, which is exactly the behaviour you want.

Reference architecture

Most vector databases now support hybrid search natively, so you rarely need a separate search engine. In Qdrant you store a dense and a sparse named vector per point and fuse server-side with the Query API. Weaviate, LanceDB, turbopuffer, Milvus and Pinecone all offer some form of keyword or sparse plus dense search. With Postgres you can pair pgvector with full-text search (tsvector) or a BM25 extension and fuse in SQL or application code.

Rendering diagram…

Fetch more from each branch than you finally need (for example 50 each, fuse to 20, rerank to 5). Fusion can only promote documents that at least one retriever found.

Code

Qdrant with Python: one request, two prefetch branches (sparse and dense), fused with RRF on the server.

from qdrant_client import QdrantClient, models

client = QdrantClient(url="http://localhost:6333")

client.create_collection(
    collection_name="docs",
    vectors_config={"dense": models.VectorParams(size=1024, distance=models.Distance.COSINE)},
    sparse_vectors_config={"sparse": models.SparseVectorParams()},
)

def hybrid_search(dense: list[float], sparse_idx: list[int], sparse_val: list[float], k: int = 20):
    return client.query_points(
        collection_name="docs",
        prefetch=[
            models.Prefetch(
                query=models.SparseVector(indices=sparse_idx, values=sparse_val),
                using="sparse",
                limit=50,
            ),
            models.Prefetch(query=dense, using="dense", limit=50),
        ],
        query=models.FusionQuery(fusion=models.Fusion.RRF),
        limit=k,
        with_payload=True,
    ).points

And if your two retrievers live in different systems, RRF is a few lines in TypeScript:

export function reciprocalRankFusion(lists: string[][], k = 60, topN = 20): string[] {
  const scores = new Map<string, number>();
  for (const list of lists) {
    list.forEach((id, index) => {
      scores.set(id, (scores.get(id) ?? 0) + 1 / (k + index + 1));
    });
  }
  return [...scores.entries()]
    .sort((a, b) => b[1] - a[1])
    .slice(0, topN)
    .map(([id]) => id);
}

Trade-offs and pitfalls

  • Tokenization matters for BM25. Default analyzers may split "ERR-4012" into "err" and "4012", or stem away meaningful suffixes. Check how your identifiers are tokenized and add a keyword field if needed.
  • Language support. BM25 needs per-language stemming and stopwords. For multilingual corpora a learned sparse model or a multilingual analyzer is often easier.
  • RRF ignores score magnitude. A retriever that is very confident about one result gets no extra credit. If one retriever is clearly better for your traffic, weighted fusion or a reranker can capture that.
  • Weighted fusion needs tuning per traffic type. An alpha that suits natural-language questions may hurt part-number lookups. Some teams route queries (identifier-like versus question-like) to different weights.
  • Fusion is not reranking. Fusion merges lists cheaply; a cross-encoder reranker then reads query and chunk together. They are complementary stages.
  • Keep both indexes in sync. Deletes and updates must hit the sparse and dense sides together, or fused results will reference stale chunks.

Checklist

  • Add a lexical or learned sparse retriever alongside dense retrieval.
  • Verify tokenization of identifiers, codes and names in your BM25 analyzer.
  • Start with RRF (k = 60) before trying tuned weighted fusion.
  • Over-fetch from each branch, fuse, then rerank.
  • Evaluate hybrid against each retriever alone on separate query slices (keyword-like and natural-language).
  • Keep sparse and dense representations updated in the same write path.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.