Inferensys

Glossary

BM25

BM25 (Best Matching 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 algorithm for keyword search.
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.
INFORMATION RETRIEVAL

What is BM25?

BM25 (Best Matching 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 algorithm for keyword search.

BM25 (Okapi BM25) is a probabilistic retrieval function that ranks documents by estimating the probability of relevance to a query. It refines the classic TF-IDF (Term Frequency-Inverse Document Frequency) approach by introducing non-linear term frequency saturation and document length normalization. This prevents very long documents from dominating results simply by containing many query term repetitions, making it the de facto standard for lexical or keyword-based search in modern systems like Elasticsearch and Lucene.

The algorithm calculates a score for each document by summing the BM25 weights of all query terms present. Its key parameters control term frequency saturation (k1) and document length normalization (b). In hybrid search architectures, BM25 scores are often fused with vector similarity scores from dense retrieval models. This combination leverages precise keyword matching for exact concepts and semantic understanding for paraphrases or related ideas, forming a robust multi-stage retrieval pipeline.

PROBABILISTIC RANKING FUNCTION

Key Features of BM25

BM25 (Best Matching 25) is a state-of-the-art probabilistic ranking algorithm that estimates the relevance of documents to a search query based on term frequency, inverse document frequency, and document length normalization.

01

Probabilistic Relevance Framework

BM25 is grounded in the probabilistic relevance model (PRP), which ranks documents by their estimated probability of being relevant to a query. Unlike simpler heuristics, it models relevance as a probability distribution, making it robust across diverse corpora. The core formula is derived from Robertson-Sparck Jones weight, incorporating term frequency saturation and document length normalization to avoid over-weighting repetitive terms or very long documents.

02

Term Frequency Saturation

BM25 uses a non-linear saturation function to dampen the impact of excessively high term frequencies within a single document. This prevents a document mentioning a query term dozens of times from disproportionately dominating the results. The saturation is controlled by the k1 hyperparameter.

  • Low k1 (e.g., 1.2): Strong saturation, favoring documents where the term appears a moderate number of times.
  • High k1 (e.g., 2.0): Weaker saturation, allowing term frequency to have a larger linear influence on the score.
03

Inverse Document Frequency (IDF)

The algorithm applies an inverse document frequency component to weight terms by their discriminative power. Terms that appear in many documents (common words) receive a low weight, while rare terms that appear in few documents receive a high weight. This is calculated as: IDF(q_i) = log( (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 q_i. The constants smooth the score for terms that appear in very few or very many documents.

04

Document Length Normalization

BM25 normalizes scores based on document length relative to the average document length in the corpus. This counteracts the tendency for longer documents to accumulate higher term frequencies by chance. The normalization is controlled by the b hyperparameter.

  • b = 0: No length normalization.
  • b = 1: Full length normalization.
  • Typical b = 0.75: A balanced default that penalizes very long documents while not overly favoring very short ones. The normalization is integrated directly into the term frequency component of the formula.
05

Field-Aware Variants (BM25F)

BM25F (Fielded BM25) extends the classic algorithm to structured documents with multiple fields (e.g., title, body, author). Each field can be assigned a field-specific boost weight, and term frequencies are aggregated across fields according to these weights before being fed into the core BM25 formula. This allows the ranking to prioritize matches in important fields like a title over matches in a large body text field, providing more nuanced and controllable relevance tuning for semi-structured data.

06

Hyperparameter Tuning (k1 & b)

BM25's effectiveness is highly dependent on tuning its two core hyperparameters, k1 and b, to the specific document collection.

  • k1 controls term frequency saturation. Values typically range from 1.2 to 2.0. Tune higher if term frequency is a strong relevance signal in your domain.
  • b controls document length normalization. Values range from 0 to 1, with 0.75 being a common default. Increase b if longer documents in your corpus are systematically less relevant. Optimal values are found through information retrieval evaluation on a labeled dataset, using metrics like nDCG@10 or MAP.
RETRIEVAL ALGORITHM COMPARISON

BM25 vs. TF-IDF vs. Dense Retrieval

A technical comparison of three core information retrieval algorithms, highlighting their underlying mechanisms, performance characteristics, and optimal use cases.

Feature / MetricBM25 (Lexical)TF-IDF (Lexical)Dense Retrieval (Semantic)

Core Mechanism

Probabilistic relevance function estimating the odds a document is relevant to a query.

Term Frequency-Inverse Document Frequency: a statistical weight reflecting a term's importance.

Neural embedding similarity (e.g., cosine) between dense vector representations of query and document.

Query Understanding

Exact term matching with term frequency saturation and length normalization.

Exact term matching weighted by collection statistics.

Semantic understanding via neural networks; handles synonyms and paraphrases.

Representation

Sparse, term-based vector (implicitly).

Explicit sparse vector (bag-of-words).

Dense, low-dimensional vector (e.g., 768 dimensions).

Out-of-Vocabulary Handling

❌ Fails on unseen query terms.

❌ Fails on unseen query terms.

✅ Generalizes to semantically related unseen terms.

Indexing Speed

Fast

Fast

Slower (requires embedding generation)

Query Latency

< 10 ms

< 10 ms

10-100 ms (includes embedding time + ANN search)

Typical Recall on Semantic Queries

Low to Medium

Low

High

Primary Use Case

Precise keyword search where query terms are expected to appear in relevant documents.

Foundational weighting scheme for simple keyword search; often a baseline.

Semantic search where user intent and document meaning are more important than exact keyword matches.

Common Integration

First-stage retrieval in hybrid search pipelines, often combined with dense retrieval.

Less common in modern systems, superseded by BM25 for keyword search.

First-stage semantic retrieval or as a component in a bi-encoder + cross-encoder reranking pipeline.

APPLICATIONS

Where is BM25 Used?

BM25 is a foundational algorithm for keyword-based information retrieval. Its probabilistic design and efficiency make it a core component in numerous modern search systems.

02

Hybrid Search Architectures

BM25 is a key pillar in hybrid search systems, where it is combined with dense vector retrieval (semantic search). This approach mitigates the weaknesses of each method: BM25 excels at exact keyword and term-frequency matching, while vector search captures semantic meaning.

  • First-Stage Retrieval: Often used as a fast, recall-oriented retriever to generate a candidate set.
  • Score Fusion: Its scores are normalized and combined with vector similarity scores using techniques like Reciprocal Rank Fusion (RRF) or weighted summation.
  • Result: Improved overall recall and precision, especially for queries containing specific named entities, codes, or rare terms.
03

Web Search Engines

While modern web search employs immensely complex ranking systems, BM25 and its conceptual predecessors form a critical baseline. It addresses the fundamental term frequency and inverse document frequency signals.

  • Historical Foundation: Early web search algorithms were built upon probabilistic models like BM25.
  • Component Signal: In large-scale learning-to-rank systems, features derived from BM25 (e.g., query term coverage, TF-IDF variants) are fed as inputs to machine learning models that finalize ranking.
  • Function: Provides a robust, interpretable measure of lexical relevance before other signals (PageRank, user behavior, freshness) are applied.
04

E-commerce & Product Search

Product catalogs require search that understands precise specifications, SKUs, and model numbers. BM25 is highly effective for this lexical matching need.

  • Filtered Search: BM25 is frequently executed within a subset of products defined by metadata filters (e.g., category='laptops', price<1000).
  • Handling Sparse Data: Effective for matching unique product attributes, serial numbers, and part codes where semantic similarity is less relevant.
  • Example: Searching for "iPhone 14 Pro Max 256GB Sierra Blue" relies heavily on exact term weighting that BM25 models well.
05

Academic & Legal Document Retrieval

In domains where terminology is precise, citations are key, and wording is exact, BM25 provides deterministic retrieval based on term presence.

  • Citation Search: Finding papers that mention specific methodologies or chemical compounds.
  • Legal Discovery: Retrieving contracts or case law containing exact clauses or statutory references.
  • Advantage: Its probabilistic score is interpretable; a high score clearly correlates with strong term overlap, which is often a legal or scholarly requirement.
06

RAG (Retrieval-Augmented Generation) Systems

In RAG pipelines, the quality of the retrieved context dictates the quality of the generated answer. BM25 is often used in hybrid retrievers to ensure key factual terms from the user query are present in the sourced documents.

  • Mitigating Semantic Drift: If a user query contains a specific name, date, or number, a pure vector search might retrieve semantically similar but factually incorrect documents. BM25 grounds the retrieval in literal term matching.
  • Multi-Stage Retrieval: Can be used as a fast, broad retriever before a more computationally expensive cross-encoder reranker.
  • Outcome: Improves the factual consistency and citation accuracy of the final generated response.
BM25

Frequently Asked Questions

BM25 (Best Matching 25) is the dominant probabilistic ranking algorithm for keyword search. These FAQs address its core mechanics, applications, and how it compares to modern semantic search techniques.

BM25 (Best Matching 25) is a probabilistic ranking function used in information retrieval to estimate the relevance of documents to a given search query based on keyword matching. It works by scoring each document using a formula that considers:

  • Term Frequency (TF): How often a query term appears in the document, with diminishing returns for excessive repetitions.
  • Inverse Document Frequency (IDF): How rare or common a term is across the entire corpus, giving more weight to distinctive terms.
  • Document Length: It normalizes scores by document length, preventing longer documents (which naturally contain more words) from being unfairly favored, using a tunable parameter (b).

The core formula is: score(D, Q) = Σ(i=1 to n) IDF(q_i) * (f(q_i, D) * (k1 + 1)) / (f(q_i, D) + k1 * (1 - b + b * |D| / avgdl)) where k1 and b are free parameters, f is term frequency, |D| is document length, and avgdl is average document length. It is the state-of-the-art algorithm for lexical search or sparse retrieval.

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.