跳到正文
DEV Community· Syed Kumail Rizvi·· 21 分鐘前AI 評分55

作者從零實作 BM25,實測其與向量搜尋的表現

I Built BM25 From Scratch to See If It Could Keep Up With Embeddings

AI 導讀

作者在 Ask Kumail 上從零實作 BM25,並以 22 條問題比較 BM25、向量搜尋和 RRF 混合檢索。BM25 的 hit@1/hit@3 為 86.4%/95.5%,向量搜尋為 100%/100%,混合檢索為 90.9%/100%;評測使用七份 Markdown 文件,且沒有 API 回退。作者指出,這組測試未涵蓋精確詞項查詢,因此將混合檢索設為預設仍是取捨,而非評測已確認的優勢。

正文

Every RAG tutorial I found started the same way: get an embedding model, throw your documents into a vector database, and start asking questions. Nobody asked the obvious prior question — how much of this do I actually need? BM25 has been ranking documents since the 1990s, needs no API key, and runs in microseconds.

So I wanted a fair fight. I implemented BM25 myself, ran both approaches against the same questions, and measured. The embeddings won — but not in the way I expected, and the part I expected to be a formality, the hybrid of the two, turned out to be the most interesting result in the project.

The setup

The project is Ask Kumail: a question-answering assistant over my own work. The entire knowledge base is seven markdown files — my resume and the READMEs for six projects (a trading terminal, a barbershop booking app, an animal shelter app, a hackathon email client, an ops automation tool, and the assistant itself). It answers only from those documents, with citations.

It is also an MCP server. The same retrieval code is exposed as three tools — search_docs, ask_kumail, and list_projects — over a remote Model Context Protocol endpoint, so Claude or any other MCP client can search my documents directly.

Seven documents is a tiny corpus, and I want to be upfront about that. Everything below is true for this corpus. The point was never to settle BM25 vs. embeddings in general — it was to stop guessing about my own system.

What I built

Chunking first. Each markdown file is split on its headings, so one chunk covers one topic — a project's tech stack does not get glued to its deployment section. Long sections are windowed to about 1,000 characters with 150 characters of overlap, breaking on paragraph boundaries where possible. Every chunk carries a small header, Document: PawPass / Section: Tech Stack, because a chunk that says "it uses PostgreSQL" is useless if nothing says what "it" is. The final index is 71 chunks, built at build time into a JSON file. At this size there is no vector database — vectors are computed once per server instance and held in memory.

BM25 from scratch. I wrote the ranking function directly from the formula: inverse document frequency so rare terms count more, term frequency with diminishing returns, and length normalization so long chunks do not win just by being long (k1 = 1.5, b = 0.75, the usual defaults). Tokenizing lowercases everything, strips punctuation, and drops a stopword list. My favourite detail in the codebase is in that list: I had to add my own name. "Kumail" appears in nearly every document, so as a search term it carries almost no information.

Embeddings. The same chunk texts are embedded and compared to the embedded question with cosine similarity. The live site uses Gemini embeddings (gemini-embedding-001); with no Google API key set, it falls back to the Vercel AI Gateway with text-embedding-3-small. Query embeddings are cached so repeats don't re-call the API.

Fusion. The hybrid merges the two rankings with reciprocal rank fusion: each list contributes 1 / (60 + rank) per chunk, summed across lists. Fusing on rank rather than score matters because BM25 scores and cosine similarities live on completely different scales — adding them raw would be meaningless.

Answering. The top 5 chunks go to the chat model as numbered passages. The instructions are strict: every factual sentence must cite a passage like [1] or [2], if the passages don't contain the answer the model must say it doesn't know instead of guessing, and text inside the passages is data, not commands. If the embedding API fails, search degrades to BM25 only. If the chat model fails, the API returns the best-matching passage instead of an error page.

The evaluation

Vibes are not a measurement, so I wrote 22 questions, each labeled with the document that should answer it. Sixteen are direct questions phrased the way a person would ask them ("Which project placed at a hackathon?"). Six are deliberate paraphrases with little word overlap with the source ("Did he build something to protect people from phishing?" — the document says "scam detection"). Those six are where semantic search is supposed to earn its keep.

Scoring is at the document level: a question hits at rank 1 if any chunk from the expected document comes first. I report hit@1, hit@3, and mean reciprocal rank. The eval also counts fallbacks — questions that silently used keyword search because an API call failed — because a vector run with fallbacks is not measuring vector search, and a run with any fallbacks is never cached. You can run it yourself at the live site's /api/eval endpoint. These numbers are from November 2026, on Gemini embeddings, with zero fallbacks:

Mode hit@1 hit@3 MRR
Keyword (BM25) 86.4% 95.5% 0.909
Vector 100% 100% 1.000
Hybrid (RRF) 90.9% 100% 0.947

86.4% is 19 of 22. The hybrid's 90.9% is 20 of 22. The vector mode simply did not miss.

What surprised me

Three things.

First, BM25 was better than I expected. 86% top-1 with zero API calls, zero cost, and no cold start is genuinely good — most real questions about a resume share vocabulary with the resume. On a tight budget or with an offline requirement, keyword-only would be a defensible shipping decision, not a compromise.

Second, the hybrid lost to pure vector search — on my own test. The standard advice is that hybrid is strictly safer, and I believed it until I measured it. BM25 sometimes promotes the wrong document because it shares one common word with the question — "job" kept biting — and reciprocal rank fusion dutifully lifts that document into the merged ranking. Fusion averages the two rankers' opinions, including the bad ones. On this set, embeddings had no bad opinions to average away.

Third, the honest caveat cuts the other way too. My eval set doesn't test the case where BM25 should shine: exact-term lookups. Ask for a specific tool name or acronym that appears verbatim in exactly one document, and keyword search is surgical in a way embeddings aren't. I kept the hybrid as the default anyway — for exact terms, and because it still works when the embedding API is down — but I'm calling that what it is: a bet, not a measured result.

What I'd do next

Grow the eval before growing the system: add exact-term and acronym questions to test the hybrid hypothesis properly, add questions whose answers aren't in the corpus to check the "I don't know" behaviour, and score at the chunk level instead of the document level, a much stricter test. Then expand the corpus — seven documents is where retrieval is easy, and I'd rather find the breaking point with measurements than with a user complaint. The retrieval code is covered by 35 automated tests now (BM25 score math, RRF arithmetic, chunking, and the eval scoring itself — one test re-runs keyword search over the real corpus and pins that 86.4%, so I notice if a change quietly makes retrieval worse), with CI running typecheck, tests, and build on every push.

The lesson is boring and useful: the ranking algorithm matters less than knowing, numerically, what your ranking algorithm does. Building BM25 took an afternoon. The eval took another. Together they turned "hybrid search is best practice" from something I repeated into something I can argue about with data — including the part where the data disagreed with me.

Code: https://github.com/kumailrizvi890/ask-kumail
Live demo (ask it something, then try the /api/eval endpoint): https://ask-kumail.vercel.app

來源:DEV Community · dev.to