I Built BM25 From Scratch to See If It Could Keep Up With Embeddings
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 n
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
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.