# One error code broke through vector retrieval, and I restored BM25

Date: 2026-08-03
Category: Technology
Tags: Retrieval, RAG, BM25
Summary: After a single error-code lookup punched through vector retrieval, I added a BM25 path. A record of dual-path recall, RRF fusion, parameter trade-offs, and the judgment process on a small evaluation set.

I didn't believe this at first. We already have embeddings—why keep an old-fashioned term-frequency channel? That was until a single error code punched a hole through my internal document retrieval.

## That string that couldn't be found

The scenario isn't complicated: an internal knowledge base with a few thousand documents, mixing Markdown and ticket records. The vector store uses a fairly mainstream Chinese embedding model, chunks around 500 characters with 80 overlap. Day to day it performs well—when employees ask "how many days does reimbursement take" or "how do I request permissions for the test environment," it basically hits.

Then someone searched for `ERR_SSL_PROTOCOL_ERROR`.

The top ten results were all generic talk about "HTTPS configuration" and "certificate renewal," none pointing precisely to the troubleshooting record that actually contained this error code. I manually grepped the store—the document was right there, and the term appeared quite frequently.

At first I thought it was a chunking problem, so I shrank the chunks and increased the overlap. No help. Only later did I realize: before this string enters the embedding model, it goes through BPE (byte-pair encoding) tokenization and gets split into fragments like `ERR` `_S` `SL` `_PRO` `TOCOL`. The model has never seen this combination, and the resulting vector is very close to that of a natural-language sentence like "what to do about SSL certificate errors." Semantically it is indeed close, but what the user wants is the one exact match.

Vector retrieval solves "similar meaning," while this query wants "identical literal text." These are two things one model can't do well at the same time.

## The two channels fail differently

This is the core of how I now understand hybrid retrieval: it's not about which is more accurate, but that they fail differently.

BM25's failure mode is clear—it only looks at terms. If a user searches "how do I stop the test environment from auto-sending emails" and the document says "disable notification push," the terms don't match and BM25 recalls nothing. Chinese also needs tokenization first—`jieba` or ES's `ik`—and the granularity itself loses information.

Vector failure is more insidious—it has almost no discriminative power for long-tail tokens. I've collected deduplicated failed queries over time, and they roughly fall into these categories:

- Error codes, exception class names: `NullPointerException`, `E1004`
- Internal IDs: ticket numbers, requirement numbers, of the form `REQ-2024-0871`
- Model and version numbers: `v2.3.1-rc2`
- Rare proper nouns: the codename of some internal system
- Queries with negation: "how to archive emails that don't contain attachments"—vectors tend to latch onto just "archive emails"

The reverse also holds. When a user phrases a question three different ways, or uses colloquial language like "nothing happens after I upload the thing," while the document says "upload timeout," BM25's vocabulary gap shows up.

The overlap between these two failure sets is actually small. I roughly tallied my own failure samples: of the ones pure vector missed, BM25 recovered more than half; of the ones BM25 missed, vectors recovered most. That's the real source of "almost always better"—it's not that each channel is strong, but that the two channels' errors are uncorrelated.

## For the fusion step, RRF is less hassle than tuning weights

After dual-channel recall, how to merge—I tried two approaches.

The first was score weighting, `final = α * bm25_score + (1 - α) * cosine`. Theoretically sound, practically annoying: BM25 scores have no upper bound—a document matching multiple terms can reach ten or twenty points—while cosine usually squeezes into the narrow 0.5 to 0.9 range. Adding them without normalization means listening entirely to BM25; with min-max normalization, extreme values skew it, and you have to retune α every time you change the corpus. I tuned for two days and felt like I was creating work for myself.

Then I switched to RRF (Reciprocal Rank Fusion), which only uses ranks, not scores:

```python
def rrf_fuse(rankings, k=60, top_n=20):
    # rankings: [[doc_id, doc_id, ...], ...] 每路召回一个有序列表
    scores = {}
    for ranked in rankings:
        for rank, doc_id in enumerate(ranked, start=1):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
    return sorted(scores.items(), key=lambda x: -x[1])[:top_n]
```

`k` set to 60 is a common default in the literature. I ran the eval set with 30 and 60, and at my scale the difference was under two points, so I kept 60. RRF's advantage is not worrying about inconsistent score scales between the two channels, and not retuning parameters when you change models. The downside is losing the absolute information in scores—for example, the difference between vector similarity 0.95 and 0.62 gets flattened. In my scenario that's not a problem, because vector scores are already narrowly distributed with limited discriminative power.

What really needs tuning is how many results each channel recalls. My current config recalls 50 per channel, takes the top 20 after fusion, then passes them to rerank. At first I took 20 per channel and found some documents ranked in the 30s in a single channel disappeared after fusion. Fusion's advantage comes precisely from "ranked low in one channel, high in the other"—insufficient recall depth means you've blocked that path yourself.

### Pitfalls I hit with tokenization and parameters

BM25 looks simple, but in the Chinese scenario a few things are worth mentioning.

For the tokenizer I use `ik_max_word` for indexing and `ik_smart` for querying—the standard ES practice: the former splits finer with higher recall, the latter splits coarser with higher precision. But it doesn't recognize internal codenames and splits them apart. I maintain a custom dictionary with system codenames, common error-code prefixes, and product names. The effect was immediate—about thirty terms pulled recall for that query type up substantially.

On parameters, ES defaults are `k1=1.2` and `b=0.75`. `b` controls the strength of document-length normalization; at `b=1` it fully penalizes long documents by length. My store has huge length variance—short ticket records of two or three hundred characters, long operation manuals of tens of thousands. Under defaults, long documents suffer badly. Setting `b` to around 0.5 helped; the reasoning is that when the target term appears in a long manual, it's often genuinely relevant and shouldn't be suppressed so harshly. I didn't do systematic optimization on this value—it's a guess plus verification. If anyone has a more reliable method, let me know.

Another pitfall is fields. At first I concatenated title and body into one field for BM25, and terms in the title got diluted by the body. Later I split them into `title` and `body` fields, and added a `boost` of about 2 to 3x to title at query time—the effect was much more pronounced than tuning `k1`.

## How I actually judge whether it got better

I think this part matters more than choosing a model.

I built a small eval set of 120 queries, sourced from real user search logs plus boundary samples I created myself, with 30 specifically reserved for the "vector will inevitably fail" query types above. For each query I manually labeled the relevant document IDs, only marking which ones should appear in the top 20 positions. Then I ran three configs in a script: pure BM25, pure vector, and hybrid, looking at recall@20 and MRR.

The results were roughly this: pure vector recall@20 around 0.72, pure BM25 around 0.65, hybrid around 0.89. Broken down by query type it's more interesting—on those 30 "vector fails" samples, pure vector was just over 0.3, while hybrid reached above 0.85. And pure BM25 losing to vector overall is mainly due to the colloquial-query tier.

This evaluation is not rigorous, the sample size is small, and I did all the labeling myself, so it carries my bias. But it at least let me answer one question: is the maintenance cost of adding this BM25 path worth it? For me, yes, because what it adds is one ES index and one custom dictionary—no extra model service.

### When I would not add it

To be fair, there are scenarios where I think pure vectors are enough.

If the corpus is all long-form natural language—say, a batch of prose-style meeting minutes or interview transcripts—and the queries are all colloquial descriptions, then BM25's marginal contribution will be small, and adding another path only increases the operational surface. Conversely, if the corpus consists of structured short entries full of IDs, codes, and parameters, then BM25 can even be the primary path, with vectors serving only as a fallback.

The way to judge this is not complicated either: pull a hundred real queries from the logs, run pure vectors first, pick out the misses, and see how many of them are cases where "the literal text matches but the semantics don't." If that proportion exceeds twenty or thirty percent, you can basically conclude that a lexical retrieval path should be added.

My default approach now is to go dual-path whenever I build retrieval, rather than doing pure vectors first and adding the other path later. That later addition usually comes after users have already complained for a round.

Further reading: [A few questions to tell whether someone has done RAG](/2025/01/21/llmlarge-model-ai-interview-rag-vector-search-alignment-evaluation-hal/), [Before switching embeddings, look at those seventy percent bad cases](/2025/04/30/rag-vector-store-pitfalls/)
