# Hybrid retrieval: the value of two paths lies in erring differently

Date: 2025-06-13
Category: Technology
Tags: RAG, Hybrid Retrieval, BM25
Summary: The value of two-way retrieval lies not in which is more accurate, but in the small overlap of their failure sets. From the several knobs of BM25 and the pitfalls of score normalization to RRF and routing by query type, this explains clearly how hybrid retrieval should be configured and when it is not worth adopting.

I once wrote a short piece on how a single error code `ERR_SSL_PROTOCOL_ERROR` broke pure vector retrieval ([BM25 and vectors aren't competitors, they're complements](/2026/08/03/hybrid-retrieval-bm25-plus-vector/)). That piece covered the symptom; this one covers the mechanism: why this kind of failure is structural, what information each fusion approach throws away, and when it's worth adjusting weights by query type.

Let me state the conclusion up front: **the payoff of hybrid retrieval doesn't come from "both channels being strong," it comes from the two channels' failure sets overlapping little enough**. If both channels fail together on the same batch of queries, combining them just makes the answer more expensive.

> Post 8/15 in this series · [Previous: The four axes of vector database selection](/2025/12/05/vector-database-ann-index-selection/) · [Next: Reranking: the gains and costs of a two-stage architecture](/2025/08/04/reranking-two-stage-retrieval-architecture/)

## Why dense retrieval can't catch strings that match literally

As mentioned in post 6, a bi-encoder compresses an entire passage into a fixed-dimensional vector. That compression pays off for high-frequency semantics, but it's not kind to rare literal tokens.

Strings like error codes, ticket numbers, and model numbers get split by BPE tokenization into fragments like `ERR` `_S` `SL` `_PRO` `TOCOL`, and the model has barely seen such combinations in its training corpus. The resulting vector lands near natural-language phrases like "SSL certificate error" — semantically close, yes, but what the user wants is an exact hit on the document that contains this error code. In vector space, "similar meaning" is continuous similarity, while "identical literal" is a set-membership test, and dense vectors can't express the latter.

The reverse failure is just as clear. BM25 only knows words: when the user says "nothing happens after I upload the thing" and the document says "upload timeout," the moment a vocabulary gap appears, the term-frequency channel recalls nothing. I've categorized the failed queries I've collected:

| Query type | Dense | BM25 |
| --- | --- | --- |
| Error codes, exception class names, IDs, version numbers | Weak | Strong |
| Rare proper nouns, internal system codenames | Weak | Medium (depends on tokenization) |
| Colloquial descriptions, rephrasings, conceptual questions | Strong | Weak |
| With negation, multi-condition combinations | Weak (tends to grab only the main noun) | Medium |
| Short queries (2–4 characters) | Medium | Medium (highly ambiguous) |

This table is more useful than any "hybrid retrieval improves X%" conclusion, because it directly guides routing: if a query contains uppercase strings, hyphenated IDs, or version-number patterns, raise the weight of the sparse channel — no need to wait for both channels to finish and then compare scores.

## The few knobs in BM25 actually worth turning

The score for each query term `t` over document `d` is roughly:

```text
score(t, d) = IDF(t) · [ f(t,d) · (k1 + 1) ] / [ f(t,d) + k1 · (1 - b + b · |d| / avgdl) ]
```

`IDF` suppresses common words; `f(t,d)` is term frequency with a saturation effect; `k1` controls how fast it saturates (commonly around 1.2); `b` controls the strength of document-length normalization (commonly 0.75; `b=1` fully penalizes long documents by length, `b=0` ignores length). These numbers get copied so much that the copiers often don't know what they're tuning. A few practical observations.

Chinese tokenization is the first hurdle. With `jieba` or ES's `ik`, a common combination is fine-grained `ik_max_word` at index time for recall and coarse-grained `ik_smart` at query time for precision. But internal codenames and error-code prefixes are words the tokenizer doesn't recognize at all and will shatter. I've maintained a custom dictionary of about thirty words with system codenames, error-code prefixes, and product names stuffed in, and recall on these queries changed immediately. The trouble is it has to follow the business: forget to add a word when a new system launches, and retrieval degrades silently with no alert.

`b` should be tuned to the corpus's length distribution. When the library has short tickets of two or three hundred characters alongside long manuals of tens of thousands, the default 0.75 crushes long documents hard. I tried dropping it to around 0.5, on the reasoning that a target term appearing in a long manual is often genuinely relevant and shouldn't be penalized that heavily. There's no universal optimum for this kind of judgment — you can only try it against your own eval set.

Fields matter more than parameters. Concatenating title and body into one field lets body text dilute title terms; splitting them into `title` and `body` fields and giving title a 2–3x boost usually has a much more visible effect than tuning `k1`. Same for the `section_path` mentioned in post 5 — it can be used as a separately weightable field.

One step further is learned sparse representations: use a model to expand queries and documents into weighted sparse term vectors (SPLADE and the like), keeping literal interpretability while also doing query-term expansion to alleviate some of the vocabulary gap. The cost is extra model inference, a larger index, and greater sensitivity to Chinese tokenization and vocabulary design. I don't enable it by default on general document libraries — I've only tried it in scenarios with "many terms, many synonymous rephrasings, and a hard requirement for interpretability."

## The real trouble with fusion is score scale

After dual-channel recall comes merging. The most intuitive approach is weighted summation: `final(d) = α · norm(bm25_score(d)) + (1 - α) · norm(cosine(d))`.

The problem is all in `norm`. BM25 scores have no upper bound — a document matching several terms can reach ten or twenty points; cosine usually sits in a narrow band of 0.5–0.9. Adding them without normalization means listening entirely to BM25. Normalization has its own pitfalls: min-max gets skewed by outliers and depends on the current candidate set, so the same document's score isn't comparable across queries; z-score assumes a roughly stable score distribution, when in reality variances differ wildly across queries; and every time you change the corpus or the embedding model, α has to be retuned.

I spent two days tuning that weight and felt more like I was manufacturing long-term maintenance work for myself. So I switched to RRF (Reciprocal Rank Fusion), which consumes only ranks, not scores.

```python
from collections import defaultdict

def rrf_fuse(rankings, k=60, top_n=30, weights=None):
    weights = weights or [1.0] * len(rankings)
    scores = defaultdict(float)
    for ranked, w in zip(rankings, weights):
        for rank, doc_id in enumerate(ranked, start=1):
            scores[doc_id] += w / (k + rank)
    return sorted(scores, key=lambda d: -scores[d])[:top_n]

def route_weights(query):
    if looks_like_code(query):          # 大写串、连字符编号、版本号
        return [1.4, 0.6]               # 稀疏优先
    if len(query) <= 4 or is_colloquial(query):
        return [0.7, 1.3]               # 稠密优先
    return [1.0, 1.0]
```

`k` dampens the absolute advantage of top ranks; 60 is the common default in the literature. I tried 30 and 60 on my own eval set, the difference was under two points, so I kept 60.

RRF's advantage is that it sidesteps score scale entirely: changing the embedding model or BM25 parameters requires no retuning of fusion coefficients, and it naturally tolerates one channel failing wholesale — if the vector service times out and returns an empty list, the other channel still produces results after weighting. The cost is losing the absolute information in scores: the difference between 0.95 and 0.62 gets flattened. In scenarios where vector scores are already narrowly distributed, that's not much of a loss; but if scores genuinely carry confidence (say, you need a rejection threshold downstream), keep the raw scores on a separate path for that judgment — don't expect the fused RRF score to serve as confidence. It's only comparable within a single query, not across queries.

`weights` was added later to route by query type. `looks_like_code` is just a few regexes plus a whitelist—crude, but stable. Compared with training a classifier, rules are explainable, rollback-able, and when something breaks you can see at a glance why. One pitfall: don't put query rewriting before this. Unconditional rewriting is the most likely to "optimize" an exact error code into natural language, washing away the only literal clue that could match—I mentioned this in post 4.

## Recall depth, timeouts, and ID alignment

The gain from fusion comes precisely from "one route ranking it low, the other ranking it high." So each route's recall depth must be clearly larger than the final candidate count. My current config takes 50 per route, fuses to 30 for reranking, and finally sends 5–8 chunks. At first I took 20 per route, and some documents that ranked 30-something in a single route vanished entirely after fusion—effectively blocking the complementarity myself.

The two routes must run concurrently, with independent timeouts. When the vector service is flaky, the BM25 route shouldn't time out along with it, and vice versa. The degradation strategy is straightforward: if one route times out, use the other route's ranking for single-route RRF, and mark `degraded=true` in the trace so later evaluation can pull these requests out separately.

There's also a consistency issue: both routes must use the same `chunk_id` space. The BM25 index is built per document, the vector index per chunk—at fusion time the IDs don't line up, and it looks like fusion succeeded when in fact the same passage is treated as two records. I validate the ID sets on both sides at index publish time and reject the publish if they don't match.

Evaluation must be broken down by type. An overall Recall@20 gain of a few points can easily mask a trade-off like "ID-type queries up, colloquial queries down." My eval set keeps a dedicated group of "vector will necessarily fail" samples counted separately; every time I change the fusion config, I look at these groups together. Post 11 will expand layered evaluation into a full system.

## Whether to adopt it, and what it costs

On the benefit side: for rare literal strings and exact matches it's a qualitative change, not a gradual one; the two routes fail independently, so the overall recall ceiling is higher; RRF makes the system insensitive to model and parameter changes, with low maintenance cost; and when one route fails, degradation is built in.

The costs are real too: an extra index (ES/OpenSearch or a sparse index), an extra tokenizer, and a dictionary someone has to maintain; the extra latency and resources from running two routes concurrently; an extra parameter space in the fusion layer; and having to look at both routes' traces when debugging. For a personal project or small team, the added operational surface is a real cost.

When not to add it: if the corpus is all long natural-language text, the queries are all colloquial descriptions, and there are no ID-type queries, BM25's marginal contribution is small. The way to judge isn't complicated: sample a hundred real queries from the logs, run pure vector, pick out the misses, and see how many are "literal match, semantic mismatch." Below one or two tenths, don't go dual-route yet; above three tenths, it's basically confirmed you should add it. Conversely, if the corpus is structured short entries with IDs everywhere, BM25 should be the main force and dense only a fallback.

One last thing to be clear about: hybrid recall solves "is the right answer among the candidates," not "where does the right answer rank." Compressing 30 candidates into a final 5 requires a ranking that actually looks at query–document interaction—that's the next post. Why not go look at the log of your most recent query right now and see how many of the two routes' top tens overlap? The less they overlap, the more fusion is worth it.
