BM25 is a probabilistic retrieval model that scores documents based on the statistical distribution of query terms within them. It refines the classic TF-IDF (Term Frequency-Inverse Document Frequency) approach by introducing non-linear term frequency saturation and document length normalization. This means terms appearing very frequently in a single document contribute diminishing returns to the score, and the length of a document is factored in to prevent bias towards longer texts. The model's parameters, k1 and b, control term frequency scaling and document length normalization, respectively.
Glossary
BM25

What is BM25?
BM25 (Best Match 25) is a probabilistic ranking function used in information retrieval to estimate the relevance of documents to a given search query, serving as a state-of-the-art baseline for sparse retrieval.
As a sparse lexical retrieval method, BM25 operates on exact keyword matches, making it highly effective for queries where term presence is a strong relevance signal. It is computationally efficient and does not require a machine learning training phase, which is why it remains a gold-standard baseline for evaluating more complex neural retrievers. In modern Retrieval-Augmented Generation (RAG) architectures, BM25 is often used in hybrid retrieval systems, combined with dense vector search (semantic search) to improve overall recall by capturing both exact keyword matches and conceptual similarity.
Key Features of BM25
BM25 (Best Match 25) is a probabilistic ranking function that serves as the state-of-the-art baseline for sparse, term-based retrieval. Its core features are designed for robustness, efficiency, and handling real-world text phenomena.
Probabilistic Relevance Framework
BM25 is grounded in the probabilistic relevance model (Robertson/Spärck Jones), which ranks documents by the estimated probability that they are relevant to a query. It does not rely on dense vector similarity but on term frequency (TF) and inverse document frequency (IDF). The core formula calculates a relevance score for each document-query pair by summing the contributions of matched query terms, weighted by their importance across the corpus.
Term Frequency Saturation
A key innovation of BM25 over earlier TF-IDF models is its non-linear saturation of term frequency. The impact of a term's frequency within a document (TF) is controlled by the k1 parameter. As term count increases, its contribution to the score grows but quickly saturates, preventing unnaturally high scores for documents that simply repeat a query term many times. This models the principle of diminishing returns for repeated mentions of the same concept.
Document Length Normalization
BM25 incorporates field-length normalization via the b parameter to account for document size. Longer documents naturally have higher term frequencies, which could bias scores. The normalization component penalizes scores from longer documents unless the increased term frequency is proportionally significant. This allows BM25 to fairly compare documents of varying lengths, a common scenario in enterprise corpora with short reports and lengthy manuals.
Inverse Document Frequency (IDF) Weighting
Each query term is weighted by its inverse document frequency (IDF), which quantifies how informative the term is. Common terms (e.g., 'the', 'system') that appear in many documents receive a low IDF, minimizing their impact on the final ranking. Rare, specific terms that appear in few documents receive a high IDF, making them strong signals of relevance. This ensures the ranking prioritizes documents containing distinctive, query-specific vocabulary.
Parameterized Tuning
BM25 is not a single fixed formula but a family of ranking functions with tunable parameters:
k1: Controls term frequency saturation. Typical values range from 1.2 to 2.0.b: Controls document length normalization (0 to 1). A value of 0 disables normalization; 1 applies full normalization.epsilon(δ): A minor component for term frequency normalization. These parameters can be optimized on a validation set to adapt BM25's behavior to specific document collections and domains.
Efficiency & Exact Match Focus
As a sparse retrieval method, BM25 operates on inverted indices, making it extremely fast and memory-efficient for large-scale search. It excels at lexical matching and keyword search, identifying documents containing the exact query terms or their morphological variants (via stemming). This makes it highly effective for queries with specific named entities, codes, or technical jargon where precise term overlap is a strong relevance signal.
BM25 vs. TF-IDF: A Technical Comparison
A feature-by-feature comparison of two foundational lexical ranking functions used in information retrieval and RAG systems.
| Feature / Metric | TF-IDF | BM25 (Okapi BM25) |
|---|---|---|
Core Ranking Principle | Term Frequency-Inverse Document Frequency | Probabilistic Information Retrieval |
Term Frequency (TF) Saturation | Linear: TF weight increases linearly with term count. | Non-linear: Uses saturation function (parameter k1) to dampen effect of very high term counts. |
Document Length Normalization | Crude: Often uses cosine similarity for vector length normalization. | Sophisticated: Explicit parameter (b) controls penalty for long documents. |
Tunable Hyperparameters | None: Fixed formula. | Two primary: k1 (term frequency saturation) and b (length normalization). |
Theoretical Foundation | Heuristic: Based on information theory concepts. | Probabilistic: Derived from the Binary Independence Model and Robertson/Spärck Jones weighting. |
Handling of Stop Words | Ineffective: High IDF for rare stop words can artificially boost score. | Effective: Built-in inverse document frequency (IDF) component naturally downweights common terms. |
Query Term Interactions | Bag-of-words: Assumes query terms are independent. | Bag-of-words: Also assumes term independence. |
Performance on Long Queries | Standard: No special handling for query length. | Extended: BM25+ and other variants include normalization for query length. |
Typical Retrieval Effectiveness | Good baseline | State-of-the-art baseline for sparse retrieval; generally outperforms TF-IDF. |
Computational Complexity | O(|Q| * |D|) for scoring, where |Q| is query terms and |D| is document terms. | O(|Q| * |D|) for scoring; similar to TF-IDF with minimal overhead. |
Common Use Case | Simple search applications, quick prototypes. | Production search engines, baseline for academic IR, hybrid RAG retrieval systems. |
BM25 in Modern Systems & Frameworks
BM25 remains a foundational sparse retrieval algorithm, widely implemented in search engines and hybrid RAG systems for its efficiency and strong lexical matching performance.
Core Algorithm & Formula
BM25 (Best Match 25) is a probabilistic ranking function derived from the Okapi BM25 system. It scores a document (D) for a query (Q) by summing the scores of each query term. The core formula for a term t is:
score(t, D) = IDF(t) * ((f(t, D) * (k1 + 1)) / (f(t, D) + k1 * (1 - b + b * (|D| / avgdl))))
- IDF(t): Inverse Document Frequency, measuring term specificity.
- f(t, D): Term frequency within the document.
- |D|: Document length in words.
- avgdl: Average document length across the corpus.
- k1 & b: Tunable hyperparameters controlling term frequency saturation and document length normalization.
Key Hyperparameters: k1 and b
BM25's behavior is controlled by two critical hyperparameters:
- k1: Controls term frequency saturation. A lower value (e.g., 1.2) means term frequency contributes less; the score saturates quickly. A higher value (e.g., 2.0) gives more weight to repeated terms. Typical range is 1.2 to 2.0.
- b: Controls document length normalization. A value of 0.0 disables length normalization. A value of 1.0 applies full normalization, penalizing longer documents more heavily. A common default is 0.75.
Tuning these parameters is essential for adapting BM25 to different corpora (e.g., short tweets vs. long technical manuals).
Integration in Elasticsearch & Lucene
BM25 is the default scoring algorithm in Apache Lucene (since version 6.0) and Elasticsearch (since version 5.0), replacing the classic TF-IDF Vector Space Model. In Elasticsearch, it's accessed via the "similarity": "BM25" mapping parameter. Engineers can tune global or field-specific k1 and b values directly in the index settings. This deep integration makes BM25 the workhorse for full-text search in countless enterprise applications, providing a robust, production-grade baseline for lexical retrieval.
Role in Hybrid RAG Systems
In modern Retrieval-Augmented Generation (RAG) architectures, BM25 is rarely used alone. It is a key component in hybrid retrieval strategies:
- Sparse (Lexical) Retrieval: BM25 provides high precision on keyword matches and handles out-of-vocabulary terms well.
- Dense (Semantic) Retrieval: A separate vector search using embeddings captures semantic similarity.
Results from both retrievers are combined via reciprocal rank fusion (RRF) or weighted scoring to create a final ranked list. This hybrid approach maximizes recall by covering both exact term matching and conceptual understanding, improving overall RAG pipeline robustness.
Python Implementations: rank-bm25 & spaCy
For prototyping and integration into Python-based ML pipelines, several libraries offer efficient BM25 implementations:
- rank-bm25: A popular, lightweight Python package (
pip install rank-bm25) offering a simple API for indexing and querying. It's ideal for in-memory retrieval on moderate-sized corpora. - spaCy: The industrial-strength NLP library can be combined with rank-bm25 for a pipeline where spaCy handles tokenization and lemmatization, and BM25 handles retrieval.
These tools allow developers to quickly benchmark BM25 performance against dense retrievers or build custom hybrid search systems without relying on a full-scale search engine.
Benchmarking & The BEIR Benchmark
BM25's performance is rigorously evaluated as a standard baseline on benchmarks like BEIR (Benchmarking Information Retrieval). BEIR is a heterogeneous suite of 18 datasets across diverse tasks (e.g., fact-checking, question answering, bio-medical retrieval).
Results consistently show that while zero-shot dense retrievers (like Contriever) can outperform BM25 on some semantic tasks, a hybrid of BM25 + Dense Retrieval often achieves state-of-the-art results. This validates BM25's enduring value as a core component, not a legacy system, in modern retrieval evaluation.
Frequently Asked Questions
BM25 (Best Match 25) is a foundational probabilistic ranking algorithm for information retrieval. This FAQ addresses its core mechanics, role in modern search, and its critical position as a baseline for evaluating advanced systems like Retrieval-Augmented Generation (RAG).
BM25 (Best Match 25) is a probabilistic ranking function used in information retrieval to estimate the relevance of documents to a given search query based on term frequency (TF) and inverse document frequency (IDF). It works by scoring each document using a formula that rewards terms appearing frequently within the document (TF) but penalizes terms that are common across the entire corpus (IDF), with built-in saturation controls to prevent very long documents from dominating results.
The core BM25 formula for a document (D) and query (Q) is:
[ \text{score}(D, Q) = \sum_{i=1}^{n} \text{IDF}(q_i) \cdot \frac{f(q_i, D) \cdot (k_1 + 1)}{f(q_i, D) + k_1 \cdot (1 - b + b \cdot \frac{|D|}{\text{avgdl}})} ]
Where:
- (q_i) is a query term.
- (f(q_i, D)) is the term frequency of (q_i) in document (D).
- (|D|) is the document length.
- (\text{avgdl}) is the average document length in the corpus.
- (k_1) and (b) are free parameters controlling term frequency saturation and document length normalization, respectively.
- (\text{IDF}(q_i)) is the inverse document frequency, typically computed as (\log \frac{N - n(q_i) + 0.5}{n(q_i) + 0.5} + 1), where (N) is the total number of documents and (n(q_i)) is the number of documents containing the term.
This model is considered a sparse retrieval method because it operates on explicit term matches, creating a high-dimensional, sparse vector representation (e.g., bag-of-words).
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
BM25 is a core algorithm for sparse retrieval. Its performance is measured against a suite of standard information retrieval metrics that quantify recall, precision, and ranking quality.
Precision & Recall
The foundational pair of metrics for evaluating any retrieval system.
- Precision measures the fraction of retrieved documents that are relevant (correctness).
- Recall measures the fraction of all relevant documents that are retrieved (completeness).
In practice, there is a trade-off: optimizing for one often reduces the other. For BM25, tuning parameters like
k1andbdirectly affects this balance.
Mean Average Precision (MAP)
A single-figure metric that summarizes ranking quality across multiple queries by averaging Average Precision scores.
- Average Precision (AP) for a single query calculates the average of precision values at each rank where a relevant document is found.
- MAP is the mean of AP scores across all test queries. It is a standard benchmark in academic IR, heavily used in TREC Evaluation tracks, and provides a robust measure of a system's ability to rank relevant documents highly.
Normalized Discounted Cumulative Gain (NDCG)
A ranking metric that accounts for graded relevance (e.g., highly relevant, somewhat relevant, not relevant) and the position of results.
- Gain is assigned to each document based on its relevance grade.
- Cumulative Gain (CG) sums these gains.
- Discounted CG (DCG) reduces the gain of documents lower in the ranking, reflecting user behavior.
- NDCG normalizes DCG by the ideal DCG, producing a score between 0 and 1. It is the preferred metric for modern search and recommendation systems where relevance is not binary.
R-Precision
A precision metric calculated after retrieving exactly R documents, where R is the total number of relevant documents for the query in the collection.
- Formula: R-Precision = (Number of relevant docs in top R) / R.
- It is useful because it adapts to the query's inherent difficulty (number of relevant docs).
- For a perfect ranking, all R relevant documents are in the first R positions, yielding a score of 1.0. It provides a stable, query-dependent measure of early-ranking performance.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us