Module 3 · Advanced retrieval

Hybrid BM25 + dense search and RRF fusion

7 min read

Dense search understands meaning but confuses exact references; lexical search finds exact terms but ignores synonyms and other languages. Their failures are complementary — which is why combining them is, of all the techniques in this course, the one with the best gain-to-effort ratio. This lesson explains BM25, the two ways of fusing results, and measures the effect on Prism.

BM25 in 40 lines

BM25 has been the standard lexical search algorithm for thirty years. For each question term present in a passage, it adds:

score(q, d) = Σ_t IDF(t) · tf(t,d)·(k1+1) / (tf(t,d) + k1·(1 − b + b·|d|/avgdl))
  • IDF rewards rare terms: "E02" weighs much more than « bureau » (desk).
  • k1 (1.2 to 2) saturates repetition: a word repeated ten times does not count ten times.
  • b (0.75) penalizes long passages, which mechanically contain more words.

Prism implements it in a few lines to expose every term. The decisive point is tokenization — how the text is split into terms:

def tokenize(text: str) -> list[str]:
    """Minuscules, sans accents, sans mots vides, racine grossière (6 lettres).

    « garanti(e)(s) » → « garant » ; un terme contenant des chiffres (« E02 ») est gardé tel quel.
    """
    text = unicodedata.normalize("NFD", text.lower())
    text = "".join(c for c in text if unicodedata.category(c) != "Mn")
    terms = [t for t in TOKEN.findall(text) if t not in STOPWORDS]
    return [t if any(ch.isdigit() for ch in t) else t[:6] for t in terms]

(The docstring: lowercase, no accents, no stopwords, crude 6-letter stem; a term containing digits is kept as is.) Without removing accents, « livré » and « livre » do not match; without stemming, « garantie » and « garanties » are two different terms; and a term containing digits ("E02", "3x") is kept as is, because that is precisely what lexical search must find. In production, use your engine's analyzer (PostgreSQL's french full text, Elasticsearch, Tantivy…) rather than a homemade stemmer.

Complementary failures

The questions where one of the two searches fails show the complementarity:

QuestionBM25 (top 3)Dense (top 5)Expected
How do I reset my standing desk?no resultdesk-03 firstdesk-03
Do you ship to Switzerland…?no resultliv-03 firstliv-03
How long does a parcel stay at a pickup point?liv-06 firstabsentliv-06
Supplier of the Lift desk and warranty of its motors?gar-06, desk-01, fourn-01gar-06 onlyfourn-01, gar-06

BM25 finds nothing for an English question: no word in common with the French corpus. Dense search misses « point relais » (pickup point), a precise expression that the model associates with passages about delivery in general, and it only retrieves one of the two sources of a compound question.

Fusing: RRF

The scores of the two searches are not comparable: BM25 returns values from 0 to 20 or more, cosine similarity from −1 to 1. Reciprocal Rank Fusion sidesteps the problem by looking only at ranks:

def rrf(rankings: list[list[Hit]], k: int = 60, limit: int = 5) -> list[Hit]:
    fused: dict[str, float] = {}
    best: dict[str, Hit] = {}
    for ranking in rankings:
        for rank, hit in enumerate(ranking, start=1):
            fused[hit.chunk.id] = fused.get(hit.chunk.id, 0.0) + 1.0 / (k + rank)
            best.setdefault(hit.chunk.id, hit)
    order = sorted(fused, key=fused.get, reverse=True)[:limit]
    return [Hit(best[i].chunk, fused[i]) for i in order]

A passage ranked high in both lists accumulates two contributions; a passage present in only one list can still rise if it is well ranked there. The constant k (60 in the original paper) dampens the gap between first and second rank. RRF has nothing to tune in practice: on Prism, k = 1, 10 or 60 give the same recall (0.99) and MRRs within 0.02 of each other.

Fusing: weighted combination

The alternative normalizes each list's scores (here min-max to [0, 1]) and then combines them: α·dense + (1 − α)·lexical.

d, l = normalized(dense), normalized(lexical)
chunks = {h.chunk.id: h.chunk for h in dense + lexical}
scores = {cid: alpha * d.get(cid, 0.0) + (1 - alpha) * l.get(cid, 0.0) for cid in chunks}
FusionRecall@5MRR
Weighted α = 0.30.960.84
Weighted α = 0.50.990.87
Weighted α = 0.70.940.84
RRF (k = 60)0.990.82

Well-tuned weighted fusion does slightly better on MRR; badly tuned, it loses up to five points of recall. And the right α depends on the corpus, the models and the normalization: you need an evaluation set to choose it and revalidate it with every change. RRF is the right default; weighting is an optimization to be measured.

The result

ConfigurationRecall@5MRREnglishRephrasedMulti-source
BM250.740.700.000.551.00
Dense0.900.820.920.900.75
Hybrid (RRF)0.990.820.921.001.00

Hybrid search takes the best of both in every column. MRR does not improve: fusion brings the right passages into the top five, but not always to the top. That is the job of re-ranking (next lesson).

In SQL, in one query

With PostgreSQL, hybrid search fits in one query: a dense ranking, a full-text ranking (French tsvector), fused with RRF.

WITH dense AS (
    SELECT id, row_number() OVER (ORDER BY embedding <=> $1) AS rank
    FROM chunks ORDER BY embedding <=> $1 LIMIT 20
), lexical AS (
    SELECT id, row_number() OVER (ORDER BY ts_rank_cd(content_tsv, query) DESC) AS rank
    FROM chunks, websearch_to_tsquery('french', $2) AS query
    WHERE content_tsv @@ query
    ORDER BY ts_rank_cd(content_tsv, query) DESC LIMIT 20
)
SELECT c.id, c.article_id,
       coalesce(1.0 / (60 + d.rank), 0) + coalesce(1.0 / (60 + l.rank), 0) AS rrf
FROM chunks c
LEFT JOIN dense d ON d.id = c.id
LEFT JOIN lexical l ON l.id = c.id
WHERE d.id IS NOT NULL OR l.id IS NOT NULL
ORDER BY rrf DESC
LIMIT 5;

ts_rank_cd is not BM25 (in particular, it ignores IDF), but to provide a ranking to RRF, it is often enough. For true BM25 in PostgreSQL, extensions exist; dedicated databases (Qdrant, Weaviate, Milvus…) offer their own built-in hybrid search.

Key takeaways

  • BM25 finds exact and rare terms; dense search finds meaning, synonyms, other languages.
  • Their failures are complementary: hybrid search goes from 0.90 to 0.99 recall on Prism.
  • RRF fuses ranks with no normalization or tuning: it is the default.
  • Weighted fusion can do slightly better, but α must be tuned and revalidated on an evaluation set.
  • Tokenization (accents, stems, terms with digits) decides BM25's quality.

Practice

  1. Remove accent stripping from tokenize and rerun the test bench: which questions flip?
  2. Find a question in the set where BM25 ranks the right article first and dense search does not find it: why?
  3. Run the hybrid_rrf query in PostgreSQL with an English question: what does the lexical part contain?

Resources