Inferensys

Glossary

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.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
RETRIEVAL EVALUATION METRICS

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.

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.

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.

SPARSE RETRIEVAL

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.

01

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.

02

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.

03

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.

04

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.

05

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.
06

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.

SPARSE RETRIEVAL ALGORITHMS

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 / MetricTF-IDFBM25 (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.

IMPLEMENTATION & INTEGRATION

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.

01

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.
02

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).

03

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.

04

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.

05

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.

06

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.

BM25

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).

Prasad Kumkar

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.