BM25 (Best Match 25) is a probabilistic bag-of-words retrieval function that ranks documents by estimating the relevance of each document to a given search query. It improves upon classic TF-IDF by introducing term frequency saturation—a non-linear function that prevents a term occurring many times from dominating the score—and document length normalization, which adjusts scores to avoid bias toward longer documents. These mechanisms make BM25 a robust and widely adopted sparse lexical baseline for information retrieval.
Glossary
BM25

What is BM25?
BM25 is a probabilistic bag-of-words retrieval function that ranks documents based on term frequency saturation and inverse document frequency, serving as a strong sparse baseline for hybrid legal search.
In modern legal AI pipelines, BM25 is rarely used in isolation but serves as the critical sparse component in a sparse-dense hybrid retrieval architecture. Its strength lies in exact keyword matching, which is essential for locating specific statutory references, contract clause identifiers, or defined terms that dense embedding models may overlook. When combined with dense retrieval via Reciprocal Rank Fusion (RRF), BM25 ensures high recall on precise legal terminology while the dense vector search captures conceptual similarity, forming the foundation of high-integrity legal RAG systems.
Key Features of BM25
BM25 is not a single algorithm but a family of scoring functions with tunable parameters. Understanding its core components is essential for configuring effective sparse retrieval in legal search pipelines.
Term Frequency Saturation
Unlike linear TF-IDF, BM25 applies a non-linear saturation curve to term frequency. The formula tf / (tf + k1) ensures that the fifth occurrence of a legal term contributes far less than the first. This prevents keyword stuffing from dominating scores in long contracts.
- k1 parameter (typically 1.2–2.0): Controls the slope of saturation. Higher values favor repetition.
- Practical effect: A term appearing 50 times in a 200-page merger agreement is not scored 50x higher than one appearing once.
Inverse Document Frequency (IDF)
BM25 uses a probabilistic IDF formulation derived from the Robertson-Spärck Jones weight. It penalizes terms that appear in most documents while rewarding rare, discriminative terms.
- Formula:
IDF(qi) = ln((N - n(qi) + 0.5) / (n(qi) + 0.5) + 1) - Legal relevance: Common boilerplate language ("whereas", "hereinafter") receives near-zero weight, while specific statutory citations or defined terms drive ranking.
- The
+0.5smoothing prevents division by zero and avoids negative IDF values for terms appearing in more than half the corpus.
Document Length Normalization
BM25 compensates for varying document lengths using the b parameter (typically 0.75). This prevents longer documents from having an unfair advantage simply because they contain more words.
- b=0: No normalization (long documents favored).
- b=1: Full normalization proportional to average document length.
- Legal application: A 500-page appellate record is normalized relative to the corpus average, ensuring a concise 2-page memo can still rank highly if it matches the query terms precisely.
Bag-of-Words Independence
BM25 treats documents as unordered collections of terms with no positional or sequential awareness. This is both its greatest strength and limitation.
- Strength: Extremely fast indexing and retrieval, trivially parallelizable across massive legal corpora.
- Limitation: Cannot distinguish "Party A shall indemnify Party B" from "Party B shall indemnify Party A."
- Mitigation: This is precisely why BM25 is paired with dense embedding models in hybrid retrieval—the sparse model handles exact statutory citations while the dense model captures semantic order.
Elasticsearch Implementation (BM25F)
The default similarity in Elasticsearch since version 5.0 is a field-length variant called BM25F. It applies the BM25 formula independently to each field and combines scores.
- Field boosting: Title matches can be weighted higher than body text matches.
- Legal document mapping: Fields like
case_name,citation,holding, andfull_texteach receive independent BM25 scoring before fusion. - Practical tuning:
k1andbare configurable per-field, allowing practitioners to setb=0.3for title fields (minimal length penalty) andb=0.75for body fields.
No Training Required
Unlike dense retrieval models that require contrastive fine-tuning on domain-specific pairs, BM25 is a zero-shot retriever. It works immediately on any legal corpus without labeled data.
- Deployment advantage: Instant indexing of new case law, statutes, or contract repositories.
- Baseline benchmark: BM25 serves as the strong sparse baseline against which all dense and hybrid retrieval systems are measured in legal information retrieval research.
- Robustness: No embedding drift, no model staleness, no concept drift—BM25 scores are deterministic and reproducible.
BM25 vs. Other Retrieval Methods
A feature-level comparison of BM25 against dense, hybrid, and late interaction retrieval methods for legal document search.
| Feature | BM25 | Dense Passage Retrieval | Hybrid Search | ColBERT |
|---|---|---|---|---|
Matching Mechanism | Lexical (exact term overlap) | Semantic (vector similarity) | Lexical + Semantic fusion | Token-level late interaction |
Handles Synonyms | ||||
Handles Exact Citations | ||||
Requires Training Data | ||||
Query Latency | < 10 ms | 10-50 ms | 20-60 ms | 50-200 ms |
Out-of-Vocabulary Robustness | ||||
Interpretability | High (TF-IDF weights) | Low (black-box embeddings) | Medium | Medium (token scores) |
Index Size | Small (inverted index) | Large (vector store) | Large (dual index) | Very Large (token embeddings) |
BM25 in Legal AI Applications
BM25 remains a critical component in modern legal AI stacks, providing exact lexical matching that complements dense semantic embeddings. Its probabilistic framework excels at identifying precise statutory citations, defined terms, and unique contract clauses that embedding models may overlook.
Term Frequency Saturation
BM25 applies a non-linear saturation function to term frequency, preventing document length from skewing relevance. In legal documents, a term appearing 50 times is not 50x more relevant than one appearing 5 times.
- Uses the formula:
tf / (tf + k1 * (1 - b + b * doc_len / avg_len)) - Parameter
k1(typically 1.2-2.0) controls saturation steepness - Prevents keyword stuffing from gaming retrieval scores
- Critical for lengthy contracts where defined terms repeat frequently
Inverse Document Frequency in Legal Corpora
IDF gives higher weight to rare terms that carry more discriminative power. In legal search, this naturally elevates specific statutory references, party names, and unique contractual provisions over common boilerplate language.
- Formula:
log((N - n + 0.5) / (n + 0.5))where N is total docs and n is docs containing the term - Automatically down-weights ubiquitous legal phrases like "force majeure" or "indemnification"
- Elevates rare citations like "17 U.S.C. § 512(c)" that precisely identify relevant documents
- Provides strong precision for exact-match queries in large case law databases
Document Length Normalization
BM25's b parameter (typically 0.75) controls document length normalization, preventing longer legal documents from having an unfair advantage in retrieval scoring simply because they contain more words.
- Without normalization, a 200-page merger agreement would dominate a 5-page amendment
- The
bparameter balances between full normalization (b=1.0) and no normalization (b=0) - Essential for fair comparison across briefs, contracts, and judicial opinions of varying lengths
- Ensures concise legal memos can compete with lengthy appellate decisions in result rankings
Hybrid Retrieval with Dense Embeddings
BM25 serves as the sparse retrieval backbone in modern legal RAG systems, paired with dense embedding models like Legal-BERT or BGE. This hybrid approach captures both exact lexical matches and conceptual semantic similarity.
- BM25 excels at finding documents containing specific case citations or statutory references
- Dense embeddings capture paraphrased legal concepts and semantically similar arguments
- Results fused using Reciprocal Rank Fusion (RRF) without requiring score calibration
- Empirical studies show hybrid retrieval improves recall@100 by 15-25% over either method alone in legal benchmarks
BM25 as a Reranker Baseline
In two-stage retrieval pipelines, BM25 often serves as the first-pass retriever that efficiently narrows a corpus of millions of legal documents to a candidate set of 100-1000 documents before a computationally expensive cross-encoder reranker refines the ordering.
- Retrieves candidate documents in milliseconds using inverted index structures
- Provides high recall at low computational cost compared to exhaustive neural scoring
- Common pipeline: BM25 → Dense Retriever → Cross-Encoder Reranker
- Production legal search systems at Westlaw and LexisNexis employ similar multi-stage architectures
Exact Citation Matching
BM25's bag-of-words approach provides deterministic exact-match capability that dense embeddings cannot guarantee. When a lawyer searches for "314 U.S. 252", BM25 will retrieve every document containing that precise citation string.
- Dense embeddings may retrieve semantically related but incorrect citations
- BM25 guarantees 100% recall for exact string matches present in the corpus
- Critical for Shepardizing and citation verification workflows
- Combines with fuzzy matching for typo-tolerant citation retrieval in practice
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.
Frequently Asked Questions
Clear, technical answers to the most common questions about the BM25 probabilistic retrieval function and its role in modern legal search architectures.
BM25 (Best Matching 25) is a probabilistic bag-of-words retrieval function that ranks documents by estimating the relevance of a document to a given search query. It works by calculating a score based on three core components: term frequency (TF) saturation, which prevents a term occurring many times from dominating the score disproportionately; inverse document frequency (IDF), which gives higher weight to rare, discriminative terms; and document length normalization, which prevents longer documents from having an unfair advantage simply because they contain more words. The '25' in the name refers to the specific iteration of the algorithm that became the standard. Unlike boolean or pure vector-space models, BM25 provides a tunable, non-linear scoring function that has proven remarkably robust across diverse text collections, including dense legal corpora where exact lexical matching remains critical for finding specific citations, defined terms, and statutory references.
Related Terms
BM25 serves as the foundational sparse component in modern legal search stacks. These related concepts define how it integrates with dense retrieval, reranking, and fusion techniques.
Sparse-Dense Hybrid Retrieval
Combines BM25's exact lexical matching with dense semantic embeddings to capture both precise keyword overlap and conceptual relevance. In legal search, this ensures a contract clause mentioning 'force majeure' is retrieved even if the query uses 'act of god'. The sparse component handles rare, high-precision terms while the dense component manages paraphrases and synonyms.
Reciprocal Rank Fusion (RRF)
An algorithm that merges BM25 and dense retrieval result lists without requiring score calibration. It computes a reciprocal rank score: 1 / (k + rank) where k is a constant (typically 60). This elegantly handles the incomparable score distributions of sparse lexical and dense semantic systems, producing a unified ranking that outperforms either method alone.
Cross-Encoder Reranker
A two-stage refinement model where BM25 retrieves a candidate set, then a cross-encoder jointly processes the query and each document to compute a fine-grained relevance score. Unlike BM25's bag-of-words independence assumption, the cross-encoder captures token-level interactions between query and document, dramatically improving precision for nuanced legal queries.
Query Expansion
Augments a user's original search with related terms before BM25 execution. In legal contexts, this might expand 'breach' to include 'violation', 'non-performance', and 'default'. Automatic query expansion using legal thesauri or generated text improves BM25's recall by bridging the vocabulary gap between how lawyers write and how they search.
Dense Passage Retrieval (DPR)
A bi-encoder architecture that encodes queries and documents into dense vectors for semantic similarity search. While BM25 excels at exact term matching, DPR captures conceptual equivalence—understanding that 'termination for convenience' and 'unilateral cancellation right' refer to the same clause type. Modern legal systems use both in parallel.
BM25 Parameter Tuning
The two key parameters—k1 (term frequency saturation, default 1.2) and b (document length normalization, default 0.75)—require domain-specific tuning for legal text. Legal documents often have extreme length variance, from short emails to 200-page contracts. Adjusting b upward penalizes long documents more heavily, preventing verbose boilerplate from dominating results.

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