BM25 (Best Matching 25) is a probabilistic retrieval function that estimates the relevance of a document to a query by calculating a weighted sum of term frequencies (TF) within the document and inverse document frequencies (IDF) across the corpus. Unlike simple TF-IDF, it introduces non-linear term frequency saturation and document length normalization to prevent very long documents from dominating results. This makes it a robust, lexical search algorithm that excels at matching exact keywords and their statistical distributions.
Glossary
BM25

What is BM25?
BM25 is a foundational probabilistic ranking algorithm used in information retrieval to score and rank documents based on their relevance to a given search query.
The algorithm's core parameters—k1 and b—control term frequency saturation and document length normalization, allowing it to be tuned for specific datasets. As a sparse retrieval method, it operates on traditional inverted indexes, making it computationally efficient and highly interpretable. In modern hybrid retrieval systems, BM25 is often combined with dense vector search to balance high recall from semantic matching with the high precision of exact term matching, forming a cornerstone of production Retrieval-Augmented Generation (RAG) architectures.
Key Features of BM25
BM25 (Best Matching 25) is a foundational probabilistic ranking function that estimates document relevance based on term frequency saturation and inverse document frequency. Its core features make it a robust, parameter-tunable algorithm for sparse, lexical search.
Term Frequency Saturation
BM25 applies a non-linear saturation function to raw term frequency (TF) to prevent very long documents from dominating the ranking simply by repeating a term many times. The core formula uses parameters k1 and b to control the saturation curve and document length normalization.
- Parameter
k1: Controls the term frequency saturation. A lowerk1(e.g., 1.2) causes faster saturation, diminishing the impact of additional term occurrences. A higherk1gives more weight to repeated terms. - Parameter
b: Controls the degree of document length normalization. Abvalue of 1.0 applies full normalization, penalizing long documents heavily. A value of 0.0 applies no length normalization. - Effect: This ensures a term appearing 10 times in a document is not considered 10 times more relevant than if it appeared once, modeling the principle of diminishing returns in information gain.
Inverse Document Frequency (IDF)
BM25 uses a probabilistic Inverse Document Frequency weighting to quantify how much information a term provides. It penalizes terms that appear in many documents across the corpus, as they are less discriminative.
The standard IDF component is: log((N - n + 0.5) / (n + 0.5) + 1) where N is the total number of documents and n is the number of documents containing the term.
- Rare Terms: Receive a high IDF score, significantly boosting the relevance of documents that contain them.
- Common Terms (e.g., "the", "is"): Receive a low or even negative IDF score, effectively filtering them out as stop words.
- This makes BM25 highly effective for keyword-stuffing resistance and prioritizing documents with distinctive, query-specific vocabulary.
Document Length Normalization
A key innovation of BM25 over earlier models like TF-IDF is its parameterized document length normalization. It addresses the tendency for longer documents to have higher term frequencies by chance.
The normalization is integrated into the TF saturation component: TF * (k1 + 1) / (TF + k1 * (1 - b + b * (doc_len / avg_doc_len)))
- Average Document Length: The score normalizes a document's length (
doc_len) against the corpus's average document length (avg_doc_len). - Tunable Bias: The
bparameter allows engineers to tune the system's bias toward longer or shorter documents. For technical documentation retrieval, a lowerbmight be preferred, while for news article retrieval, a higherbcould normalize more aggressively. - This feature is critical for fair cross-document comparison in corpora with highly variable document sizes.
Parameter Tunability
BM25 is not a single fixed formula but a family of ranking functions defined by tunable hyperparameters. This allows it to be optimized for specific domains and document collections.
Core tunable parameters:
k1: Term frequency saturation control. Typical range: 1.2 to 2.0.b: Document length normalization control. Typical range: 0.5 to 0.8.k2ordelta: (In BM25+ variants) A term-independent correction factor for query term frequency, often used to mitigate score miscalibration.
Optimization Process: Parameters are tuned on a relevance-judged dataset (e.g., using MS MARCO or TREC data) by maximizing metrics like Mean Average Precision (MAP) or Normalized Discounted Cumulative Gain (nDCG). This makes BM25 adaptable from web search to enterprise document retrieval.
Sparse, Bag-of-Words Foundation
BM25 operates on a sparse, bag-of-words representation of text. It disregards word order and syntactic structure, focusing solely on the statistical distribution of terms.
- Computational Efficiency: This sparse representation allows for extremely fast retrieval using inverted indices, where a mapping from each term to the documents containing it is pre-computed. Retrieval involves looking up query terms and summing scores.
- Vocabulary Mismatch Limitation: As a lexical model, BM25 cannot handle synonyms or conceptual matches without explicit query expansion. The query "automobile" will not match a document containing only "car".
- This characteristic is why BM25 is often paired with dense retrieval models in a hybrid search architecture, combining its precise lexical matching with the semantic understanding of vector search.
Field-Aware Variants (BM25F)
BM25F (Fielded BM25) is a major extension designed for semi-structured documents where text is organized into fields like title, body, and author. It allows different weighting of term matches depending on the field in which they occur.
How it works:
- Each field
ihas its own set of parameters (k1_i,b_i) and weight boost (boost_i). - The term frequency for a document is a weighted sum of the term's frequency in each field.
- A match in a
titlefield, for instance, can be given a much higher boost than a match in the mainbodytext.
Use Case: This is critical in enterprise settings like product search (matching in product_name is more important than in description) or academic paper retrieval (matching in title or abstract is more significant than in the full text).
BM25 vs. Other Retrieval Methods
A technical comparison of the BM25 ranking function against other prevalent retrieval paradigms, highlighting core mechanisms, performance characteristics, and suitability for different use cases.
| Feature / Metric | BM25 (Sparse/Lexical) | Dense Retrieval (Neural/Semantic) | Hybrid Retrieval |
|---|---|---|---|
Core Mechanism | Probabilistic model based on term frequency (TF) and inverse document frequency (IDF) with saturation. | Neural encoder produces dense vector embeddings; relevance is cosine similarity in vector space. | Combines scores from BM25 and dense retrieval models (e.g., weighted sum, reciprocal rank fusion). |
Query Understanding | Exact keyword matching; sensitive to spelling, synonyms, and polysemy. | Semantic matching; handles synonyms and paraphrases via contextual embeddings. | Leverages both lexical precision and semantic understanding. |
Index Type & Size | Inverted index; typically smaller, storing term-to-document mappings. | Vector index (e.g., HNSW, IVF); stores high-dimensional vectors, often larger. | Dual indexes: both inverted and vector indices, increasing storage overhead. |
Training Data Requirement | None (statistical, requires only document corpus for IDF). | Requires significant labeled query-document pairs or contrastive training data. | Requires data for tuning the dense component and potentially the fusion weights. |
Out-of-Vocabulary Handling | Poor; cannot match terms not present in the indexed corpus. | Good; can embed unseen terms based on subword components and context. | Moderate; lexical component fails, but semantic component may capture meaning. |
Computational Cost (Indexing) | Low to moderate; fast term extraction and index building. | High; requires forward passes through a neural network for all documents. | High; incurs cost of both sparse and dense indexing pipelines. |
Computational Cost (Query Time) | Very low; fast lookups via inverted index. | Moderate; requires one forward pass to embed the query, then approximate nearest neighbor search. | Moderate to high; executes both retrieval paths and fuses results. |
Interpretability / Explainability | High; relevance scores decompose to contributions from matched query terms. | Low; relevance is a similarity between opaque vectors; hard to attribute. | Moderate; can explain BM25 matches, but dense matches remain opaque. |
Typical Recall for Semantic Queries | Low; fails on paraphrases and conceptual searches. | High; excels at finding conceptually related documents with different wording. | Very High; combines the broad recall of dense search with the precision of lexical matches. |
Typical Precision for Keyword Queries | Very High; excels at exact term matching and technical terminology. | Variable; can be lower if semantic drift occurs or for highly specific terms. | High; BM25 component ensures high precision for keyword matches. |
Domain Adaptation Effort | Low; automatically adapts to corpus vocabulary via IDF. | High; often requires fine-tuning on in-domain data for optimal performance. | High; requires tuning of both components and the fusion strategy. |
Where BM25 is Used
BM25 is a foundational ranking algorithm that powers search and retrieval across a wide spectrum of modern applications, from web-scale engines to specialized enterprise systems.
Enterprise Search & E-Discovery
In legal, pharmaceutical, and corporate document repositories, BM25 is used for precise term retrieval. Its reliance on exact term matches is advantageous when searching for specific product codes, legal citations, or chemical compounds where semantic similarity can introduce error.
- Domain Examples: Searching patent databases, internal knowledge bases, and compliance documentation.
- Why BM25?: Provides deterministic, reproducible results critical for audits and litigation. Its inverse document frequency (IDF) component naturally downweights common corporate jargon while boosting rare, significant terms.
Hybrid Retrieval in RAG Systems
Modern Retrieval-Augmented Generation (RAG) pipelines often use BM25 in a hybrid retrieval setup combined with dense vector search. This approach mitigates the weaknesses of each method: BM25 handles exact keyword matches and out-of-vocabulary terms, while dense retrievers handle semantic similarity.
- Architecture: The scores from BM25 and a neural retriever are combined (e.g., weighted sum or reciprocal rank fusion) to produce a final ranked list.
- Outcome: Significantly improves recall by ensuring relevant documents are retrieved whether they match the query lexically or semantically. This is a best practice for production RAG to reduce hallucinations.
E-commerce & Product Search
Product search engines leverage BM25 to match user queries against product titles, descriptions, and SKUs. Its term frequency saturation prevents overly long product descriptions from dominating results unfairly.
- Practical Application: A search for "men's running shoes size 10" relies heavily on BM25 to match the exact keywords "running," "shoes," and "size."
- Integration: Often used as a feature in a learning-to-rank model, where its score is combined with other signals like popularity, price, and image embeddings.
Academic & Scientific Literature Search
Platforms like PubMed and Google Scholar historically used BM25-like algorithms. Searching scientific literature requires precision for technical terminology, acronyms, and author names, where BM25's lexical focus is beneficial.
- Challenge: Disambiguating acronyms (e.g., "NLP" for Natural Language Processing vs. Neuro-Linguistic Programming) often requires additional entity recognition layered on top of BM25 retrieval.
- Evolution: Many platforms now augment BM25 with citation graph analysis and metadata filtering.
Log Analysis & Security Information
Security event management (SIEM) and log analysis tools use BM25 for searching through massive streams of system logs. Engineers search for specific error codes, IP addresses, or file paths—a task suited to exact and partial term matching.
- Operational Use: Identifying all log entries containing the string "ERR_503" or a specific transaction ID.
- Performance: BM25's efficiency allows for real-time or near-real-time search across terabytes of log data, which is less feasible with heavier neural models.
Frequently Asked Questions
BM25 (Best Matching 25) is a foundational probabilistic ranking algorithm in information retrieval. These FAQs address its core mechanics, practical applications, and its role in modern search and Retrieval-Augmented Generation (RAG) systems.
BM25 is a probabilistic ranking function used by search engines to estimate the relevance of a document to a given query, based on the statistical distribution of query terms within the document corpus. It works by scoring each document using a formula that balances term frequency (TF) and inverse document frequency (IDF) with built-in saturation controls.
The core BM25 formula for a single query term is:
score(D, Q) = Σ IDF(q_i) * ( (f(q_i, D) * (k1 + 1)) / (f(q_i, D) + k1 * (1 - b + b * (|D| / avgdl))) )
Where:
f(q_i, D)is the frequency of termq_iin documentD.|D|is the document length.avgdlis the average document length in the corpus.k1andbare tunable hyperparameters.
The algorithm's key innovations are its non-linear term frequency saturation (controlled by k1), which prevents very high term counts from dominating the score, and its document length normalization (controlled by b), which penalizes or favors longer documents. The IDF component downweights terms that appear in many documents (common words). The final score for a multi-term query is the sum of the scores for each individual term.
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 operates within a broader ecosystem of techniques for processing and optimizing search queries. These related concepts are essential for building modern, effective retrieval systems.
TF-IDF
TF-IDF (Term Frequency-Inverse Document Frequency) is the foundational statistical measure upon which BM25 is built. It quantifies the importance of a word in a document relative to a collection.
- Term Frequency (TF): Measures how often a term appears in a document.
- Inverse Document Frequency (IDF): Penalizes terms that appear in many documents, as they are less discriminative.
BM25 improves upon TF-IDF by introducing non-linear term frequency saturation (so a term appearing 20 times isn't 20x more important than appearing once) and document length normalization to prevent longer documents from dominating results unfairly.
Dense Retrieval
Dense retrieval is a neural search paradigm that contrasts with BM25's lexical approach. Instead of matching keywords, it encodes queries and documents into dense vector embeddings using models like BERT or Sentence Transformers.
- Semantic Search: Finds documents with similar meaning, even without keyword overlap (e.g., 'automobile' matches 'car').
- Embedding-Based: Relevance is computed via vector similarity (e.g., cosine similarity) in a high-dimensional space.
While BM25 excels at exact term matching and out-of-domain robustness, dense retrieval excels at semantic understanding. Modern systems often use a hybrid of both for optimal recall and precision.
Query Expansion
Query expansion is a technique to improve recall by augmenting a user's original query with additional relevant terms. This directly addresses a key limitation of BM25, which relies on exact term matches.
Common methods include:
- Pseudo-Relevance Feedback (PRF): Assumes top results from an initial BM25 search are relevant and extracts frequent, discriminative terms from them to expand the query.
- Synonym Expansion: Uses lexical databases (e.g., WordNet) or contextual embeddings to add synonyms.
- LLM-Based Expansion: Leverages a large language model to generate contextually relevant paraphrases or related concepts.
Expanded queries are then re-scored by BM25, often retrieving documents missed by the original, narrower query.
Cross-Encoder Reranking
A Cross-Encoder is a neural model used to rerank candidate documents retrieved by a first-stage system like BM25. It provides a more precise, computationally expensive relevance score.
- Architecture: Takes the query and a candidate document as a single input pair and outputs a relevance score.
- Contextual Understanding: Uses full attention across the query-document pair, capturing complex semantic relationships BM25 may miss.
Typical RAG Pipeline:
- Retrieval: BM25 fetches a large candidate set (e.g., 1000 docs).
- Reranking: A Cross-Encoder scores and reorders the top candidates (e.g., top 100).
- Generation: The top 5-10 re-ranked documents are passed to the LLM for answer synthesis. This combines BM25's efficiency with a neural model's precision.
Okapi BM25F
BM25F (Fielded BM25) is a critical extension of the classic BM25 algorithm for structured documents. It allows weighting different document fields (e.g., title, body, anchor text) according to their perceived importance.
- Field-Specific Statistics: Calculates term frequencies and lengths per field.
- Weighted Aggregation: Combines field-level scores using tunable field weights (
Boost_Title,Boost_Body).
Example: In web search, a term appearing in the title field is a stronger signal than in the body. BM25F lets you boost the title score. This makes it the de facto standard for enterprise search over databases, product catalogs, and documents with metadata.
Inverse Document Frequency (IDF)
Inverse Document Frequency (IDF) is a core component of both TF-IDF and BM25 that quantifies how much information a word provides. It is defined as:
IDF(t) = log( (N - n_t + 0.5) / (n_t + 0.5) + 1 ) where N is total documents and n_t is documents containing term t.
- High IDF: Rare terms (e.g., 'esoteric') are highly discriminative and receive a high weight.
- Low IDF: Common terms (e.g., 'the', 'system') appear in many documents and are penalized.
BM25's IDF component ensures that matches on rare, specific terms contribute more to the final relevance score than matches on common stop words. This is fundamental to its probabilistic 'bag-of-words' relevance model.

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