The Retrieval Bench

BM25 Algorithm: A Practical Guide to Sparse Retrieval

BM25 Algorithm: A Practical Guide to Sparse Retrieval
bm25 algorithm explained for practical search: learn its scoring, tuning, sparse retrieval, hybrid search, and local RAG tradeoffs for small teams and...

Here is the short version: the bm25 algorithm remains one of the best first baselines for search. It is fast, interpretable, inexpensive to run locally, and surprisingly strong when a query shares important words with a document. If you are building private document search or a retrieval-augmented generation system, starting with BM25 gives you a reference point before you spend time tuning an embedding model.

The bm25 algorithm does not understand meaning in the human sense. It scores documents using term frequency, inverse document frequency, and document-length normalization. That limitation is also its strength. You can inspect why a result ranked highly, reproduce the index on a laptop, and measure changes without depending on a hosted API.

What the BM25 algorithm actually measures

BM25 is a bag-of-words ranking method. It treats a document as a collection of terms and asks how useful each query term is for distinguishing relevant documents. A rare term such as “EmbeddingGemma” generally carries more weight than a common term such as “the.” A term appearing several times helps, but repeated occurrences eventually provide diminishing returns.

The usual scoring function has three important controls. The parameter k1 determines how quickly term-frequency gains level off. The parameter b controls how strongly document length affects the score. In many libraries, k1 starts near 1.2 and b near 0.75, but those defaults are not universal truths. A support-ticket corpus, a collection of short notes, and a code-documentation index can prefer different settings.

This is where the simple baseline earns its keep. If a document contains the exact product name, error code, function name, or legal phrase in the query, lexical matching can be more reliable than a dense vector that captures broader meaning but misses an exact identifier.

Illustration for bm25 algorithm

A reproducible BM25 baseline

To test the bm25 algorithm honestly, freeze the dataset and evaluation questions before changing the retriever. For a small private-document experiment, I would record the document source, chunk size, tokenizer, stop-word policy, index library, hardware, and software version. Keep the first run boring: one document per line or chunk, a standard analyzer, and default k1 and b values.

A useful evaluation set can start with 30 to 100 queries written from real information needs. For each query, record the documents that should appear in the result set. Recall at 5 asks whether at least one relevant document appears among the top five. Mean reciprocal rank rewards putting the first relevant result near the top. These metrics answer different questions, so report both when possible.

On a typical laptop, a small BM25 index should be easy to build and query without a GPU. Libraries such as Lucene, Elasticsearch, OpenSearch, Whoosh, and rank-bm25 expose different interfaces, but the underlying ideas are similar. The engineering details still matter: tokenization can split identifiers badly, and aggressive stemming can turn distinct technical terms into the same token.

Where lexical retrieval wins

The bm25 algorithm is especially useful for queries containing exact strings. Consider a developer searching for “CUDA out of memory,” a user entering a model name such as “EmbeddingGemma 2,” or an operator looking up error code “ECONNRESET.” A dense retriever may return conceptually related text, while lexical retrieval can place the page containing the exact phrase first.

It also performs well on collections with repeated vocabulary and clear terminology. Internal API documentation, product manuals, policy archives, and issue trackers often contain the words users need. A local index can run with modest memory, keeps documents on the machine, and avoids per-query embedding costs.

That does not mean every top result is useful. If your documents contain boilerplate headers, navigation text, or duplicated templates, those terms can distort ranking. Cleaning the corpus often improves results more than changing the retrieval model. I have seen a carefully normalized index beat a more sophisticated configuration simply because it removed repeated footer text.

Where BM25 needs help

The bm25 algorithm struggles when the query and relevant document use different vocabulary. A query for “ways to reduce monthly cloud spend” might need a document titled “infrastructure cost controls.” No exact phrase guarantees a match. Synonyms, paraphrases, spelling variations, and very short queries can expose the limits of lexical scoring.

Dense retrieval addresses some of those gaps by comparing vector representations of queries and documents. A model can connect related wording even when the words do not overlap. The tradeoff is that dense retrieval introduces model choice, embedding latency, vector storage, and another set of failure modes. It can also return semantically similar but operationally wrong passages, especially when exact identifiers matter.

For that reason, I would not frame sparse versus dense retrieval as a permanent winner-take-all decision. The right comparison depends on query types, corpus language, latency targets, and the cost of an incorrect result.

Visual context for bm25 algorithm

Combining BM25 with embeddings

Hybrid search combines lexical and dense candidates or scores. One straightforward design retrieves the top 20 or 50 results from each system, then merges them using reciprocal rank fusion. RRF does not require the two systems to produce comparable raw scores. It rewards documents that rank well in either list and gives an additional advantage to documents appearing in both.

Another design normalizes BM25 and vector scores before taking a weighted sum. This can work, but score distributions change across queries and datasets, so the weight needs evaluation rather than intuition. A starting test might compare BM25 alone, embeddings alone, and hybrid weights such as 25/75, 50/50, and 75/25. Use the same query set and report recall and ranking metrics for every configuration.

In a local RAG system, hybrid retrieval can be practical on modest hardware. The sparse index handles names and exact phrases; EmbeddingGemma 2 or another embedding model handles paraphrases. A reranker can improve the final ordering, but it adds latency and memory. Measure the complete pipeline, not just retrieval quality in isolation.

Tuning without fooling yourself

Tune one variable at a time and preserve the default baseline. Test chunk sizes such as 256, 512, and 1,024 tokens only if your application actually uses chunks. Compare a few k1 and b values rather than launching a grid search over dozens of combinations. With a small evaluation set, tiny score differences can be noise.

Inspect failures manually. If a query misses because an identifier was split incorrectly, adjust analysis before adjusting k1. If long documents dominate, investigate chunking and boilerplate before assuming b is wrong. If relevant passages are present but buried at rank 20, measure a reranker or hybrid approach.

The benchmark is the conversation starter, not the verdict. A configuration that wins on a small synthetic set may lose on next month’s support tickets. Save queries, judgments, index settings, and hardware details so another developer can rerun the comparison.

A sensible starting plan

Start with a cleaned corpus and the default bm25 algorithm. Build a small judgment set from real searches, then measure recall at 5 and 10, mean reciprocal rank, query latency, and index size. Add a dense retriever only after you know which lexical failures matter. Finally, test hybrid retrieval against both single-method baselines.

This sequence keeps the project affordable and understandable. It also gives you a useful fallback when an embedding model is unavailable, too slow, or unsuitable for private deployment. In many small systems, the best architecture is not the most fashionable one; it is the one you can inspect, rebuild, and maintain on a Tuesday evening. That is why BM25 still deserves a place in the retrieval toolbox.

Updated · 2026-10-30 15:34
Feedback

No feedback yet — submit the first.

Submit feedback
© 2026 Semantic Workshop. All rights reserved. data-driven, published weekly ♥