1. Home
  2. Blog
  3. Artificial Intelligence

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 is the ranking formula behind most keyword search engines, including Elasticsearch, OpenSearch and Lucene. It scores a document higher when it contains rare query words, repeats them a reasonable amount and is not padded with filler. We built it in 25 lines of Python and tested where it shines, where it fails and how hybrid search fixes it.

10 min read
BM25 search explained with Python

Key takeaways

  • BM25 scores documents by rare query words (IDF), how often they appear (with saturation) and document length.
  • Saturation matters: in our test, 5 repeats of a word scored 1.77 and 20 repeats only 2.08, so keyword stuffing barely helps.
  • BM25 found the exact error code “E1042” instantly but returned nothing for “forgot my login”, because no document shared those words.
  • Hybrid search combines BM25 with vector search using reciprocal rank fusion, getting exact matches and meaning.

Vector search gets the attention in AI, yet nearly every production retrieval system still runs a keyword ranker next to it, and that ranker is almost always BM25. If you build search, RAG or document Q&A, understanding BM25 tells you why some queries work perfectly, why others return nothing, and why combining it with embeddings beats either alone. Everything below comes from a small implementation we ran in Python 3.13.6 on a six-document help-centre collection.

What is BM25?

BM25, short for “Best Matching 25”, is a ranking function from the Okapi information retrieval research of the 1990s. Given a query, it gives every document a relevance score from three signals: how rare each query word is across the collection, how often it appears in the document, and how long the document is compared with the average. It needs no training and no GPU, works in any language with a tokenizer, and is the default ranking in Lucene, Elasticsearch, OpenSearch and Solr.

The BM25 formula, piece by piece

score(D, Q) = Σ over query terms t of
    IDF(t) × f(t, D) × (k1 + 1) / ( f(t, D) + k1 × (1 − b + b × |D| / avgdl) )

IDF(t) = ln( (N − n(t) + 0.5) / (n(t) + 0.5) + 1 )
  • f(t, D): how many times term t appears in document D.
  • |D| and avgdl: the document length and the average length in the collection.
  • N and n(t): the number of documents, and how many contain t.
  • k1 (usually 1.2): how quickly repeated terms stop adding score.
  • b (usually 0.75): how strongly long documents are penalised.

The IDF form shown, with the “+ 1” inside the logarithm, is the one Lucene uses; it never goes negative. Each query term contributes separately, and the scores are added.

IDF: rare words carry the signal

In our six documents, “password” appeared in three, while the error code “e1042” appeared in only one. BM25 gave them IDF weights of 0.693 and 1.540. A match on a rare, specific word is strong evidence of relevance, while a common word says little. This is why an exact product code, error number or name is such a powerful query for keyword search.

Term saturation: the k1 effect

With raw word counts, a document that repeats “password” 20 times would beat everything. BM25 caps that. We calculated the term-frequency part for an average-length document with k1 = 1.2:

Times the word appears BM25 term-frequency factor
1 1.000
2 1.375
5 1.774
10 1.964
20 2.075

The second mention adds a lot, the fifth adds a little and the twentieth adds almost nothing; the factor can never exceed k1 + 1 = 2.2. That diminishing return is the main reason BM25 resists keyword stuffing far better than simple counting.

Length normalisation: the b effect

A long manual mentions most words somewhere, which would unfairly inflate its scores. The b parameter scales term frequency by document length relative to the average (15.8 words in our collection). With b = 0.75, a long document needs more mentions to earn the same score as a short, focused one. Setting b = 0 turns length normalisation off entirely.

BM25 in 25 lines of Python

import math, re

tok = lambda s: re.findall(r"[a-z0-9]+", s.lower())
D = {k: tok(v) for k, v in docs.items()}
N = len(D)
avg = sum(len(v) for v in D.values()) / N

def idf(t):
    n = sum(1 for v in D.values() if t in v)
    return math.log((N - n + 0.5) / (n + 0.5) + 1)

def bm25(query, k1=1.2, b=0.75):
    scores = {}
    for k, v in D.items():
        s = 0
        for t in tok(query):
            f = v.count(t)
            if f:
                s += idf(t) * f * (k1 + 1) / (f + k1 * (1 - b + b * len(v) / avg))
        scores[k] = round(s, 3)
    return sorted(scores.items(), key=lambda x: -x[1])

Real engines precompute an inverted index, a map from each word to the documents containing it, so they never scan every document. The scoring logic is the same. Our collection had six short help articles: password reset (d1), error E1042 (d2), password rules (d3), shipping (d4), account lockout (d5) and a spammy page that repeats “password” six times (d6).

What the test showed

Query BM25 top results Raw word count top result
reset password d1 (3.009), d6 (1.259), d3 (0.690) d6, the spam page (6 matches)
E1042 d2 (1.617), nothing else d2
locked out of my account d5 (3.570), d2 (1.617) d5
forgot my login All scores 0 All 0

For “reset password”, raw counting ranked the spam page first because it repeats the word, while BM25 put the genuinely useful reset article first with more than double the score: two different matched words plus saturation beat repetition. For the exact code “E1042”, BM25 was perfect. The interesting failures are next.

Tip: look at BM25 failures in your own logs. Queries that score zero everywhere are exactly the ones where adding semantic search pays off.

Tuning k1 and b

For the single-word query “password”, we tried four parameter settings:

k1 b Top 3 scores
1.2 0.75 d6 1.259, d1 0.934, d3 0.690
1.2 0.0 d6 1.271, d1 0.953, d3 0.693
0.5 0.75 d6 0.956, d1 0.823, d3 0.691
2.0 0.75 d6 1.538, d1 1.012, d3 0.690

Lower k1 shrank the spam page’s lead from 0.325 to 0.133, because repetitions mattered less; higher k1 widened it. The ranking stayed the same here because one word is a weak query, and real gains from tuning are usually small. The defaults k1 = 1.2 and b = 0.75 are a sensible start; tune only against a set of real queries with known answers, and fix tokenisation first, since splitting, stemming and stop words usually matter more.

Where BM25 fails

  • Different words, same meaning. “Forgot my login” scored zero everywhere, even though the password reset article answers it. BM25 matches words, not meaning.
  • Word forms. Our tokenizer treated “password” and “passwords” as different words. Real engines add stemming or lemmatisation to fix this.
  • Spelling mistakes. “pasword” matches nothing without fuzzy matching.
  • Repetition still helps a little. The spam page ranked first for the bare query “password”, though saturation kept the gap small.

BM25 vs vector search

Aspect BM25 Vector search
Matches Exact words Meaning, paraphrases
Strong at IDs, codes, names, rare terms Natural questions, synonyms
Weak at Synonyms, rephrasing Exact codes, rare jargon
Needs An index, no model An embedding model and vector store
Explainable Yes, per-term scores Harder

Vector search turns text into embeddings and ranks by cosine similarity, which is why it would connect “forgot my login” with a password reset article. The two methods fail in opposite places, which is the argument for using both.

Hybrid search with reciprocal rank fusion

BM25 scores and cosine similarities are on different scales, so you cannot simply add them. Reciprocal rank fusion (RRF) ignores the raw scores and combines positions: each document gets 1 / (k + rank) from each list, usually with k = 60, and the totals are summed.

def rrf(*lists, k=60):
    scores = {}
    for ranking in lists:
        for rank, doc in enumerate(ranking, 1):
            scores[doc] = scores.get(doc, 0) + 1 / (k + rank)
    return sorted(scores.items(), key=lambda x: -x[1])

For the query “forgot my login password”, BM25 ranked d6, d1, d3. We paired it with an illustrative semantic ranking of d1, d5, d3, the order a meaning-based model would plausibly give; it was hand-made, not from a real embedding model. RRF then ranked d1 first (0.0325), followed by d3, d6 and d5. The useful reset article rose to the top because both lists ranked it well, while the spam page that only BM25 liked dropped back. In real systems you run both searches in parallel and fuse their top 50 or 100 results.

BM25 in practice

  • Search engines: Elasticsearch and OpenSearch use BM25 by default for text fields.
  • Databases: SQLite FTS5 has a built-in bm25() ranking function. PostgreSQL’s built-in full-text ranking uses a different formula, and BM25 needs an extension (we did not run either here).
  • Python: libraries such as rank_bm25 implement it for prototypes.
  • RAG pipelines: use BM25 alongside vector retrieval over the same chunks; how you chunk matters for both, as our RAG chunking strategies test showed.

To see where retrieval fits in a full system, read our what is RAG guide and our vector database guide.

Final thoughts

BM25 has lasted for decades because it is simple, fast and remarkably good at what it does: rewarding rare, specific matches while resisting repetition and padding. Our test showed both sides clearly. It nailed an exact error code and out-ranked a spam page, yet returned nothing for a natural rephrasing. Keep BM25 for precision, add vector search for meaning, fuse them with RRF, and judge every change against real user queries.

Frequently asked questions

What is BM25 in simple terms?

BM25 is a keyword ranking formula. It scores documents higher when they contain rare query words, repeat them a sensible number of times, and are not padded with unrelated text.

What do k1 and b mean in BM25?

k1 controls how quickly repeated words stop adding score, usually 1.2. b controls how much long documents are penalised, usually 0.75, where 0 turns length normalisation off.

Is BM25 better than vector search?

Neither is better everywhere. BM25 excels at exact words, codes and names, while vector search handles meaning and paraphrases. Hybrid search combining both usually performs best.

What is reciprocal rank fusion?

A way to merge ranked lists by position instead of score. Each document gets 1 divided by k plus its rank in each list, the totals are added, and the highest total ranks first.

Does Elasticsearch use BM25?

Yes. BM25 is the default similarity for text fields in Elasticsearch, OpenSearch and Apache Lucene.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Jaccard Similarity: Formula, Python, MinHash

Jaccard similarity measures overlap between two sets as intersection over union. Work the formula, compute it in Python for words…

Read article →
Software Development

Unix Timestamp Explained: Seconds vs ms

A Unix timestamp counts seconds since 1 January 1970 UTC. Learn seconds vs milliseconds, converting in Python, JavaScript and SQL,…

Read article →
DevOps

Git Hooks: Pre-commit and Commit-msg Examples

Git hooks run scripts at key moments such as commit and push. See tested pre-commit, commit-msg and prepare-commit-msg hooks, sharing…

Read article →
Test Automation

API Testing in Python: Pytest + Requests Suite

Build an API testing suite in Python with pytest and requests: fixtures, status codes, headers, JSON schema validation, CRUD flows,…

Read article →
Software Testing

Test Design Techniques: 9 Methods + Examples

Test design techniques help you write fewer tests that catch more bugs. Learn 9 black-box, white-box and experience-based methods with…

Read article →
Databases & SQL

SQL Temporary Table: Create, Use and Drop It

SQL temporary tables store interim results for one session. Learn syntax for SQL Server, PostgreSQL, MySQL, Oracle and SQLite, session…

Read article →
Databases & SQL

SQL CROSS JOIN: Every Combination + Examples

SQL CROSS JOIN returns every combination of rows from two tables. See the row math, product variants, calendar grids that…

Read article →
Software Development

JavaScript Date: Format, Parse, Timezone Bugs

JavaScript Date explained with tested Node.js code: zero-based months, the date-only UTC parsing trap, toISOString, getTimezoneOffset, Intl formatting, date math…

Read article →
Software Development

Python Requests: GET, POST, Timeouts, Retries

Python requests explained with code tested against a local API: GET with params, POST json vs data, headers and auth,…

Read article →
Software Development

Python Deepcopy vs Copy: Fix Nested Lists

Python deepcopy vs shallow copy explained with tested code: aliasing, nested lists, the [[0]*3]*3 trap, memo and cycles, custom __deepcopy__,…

Read article →
Artificial Intelligence

TF-IDF Explained: Formula and Worked Example

TF-IDF scores a word by how often it appears in a document and how rare it is across all documents….

Read article →
Software Development

Base64 Encoding Explained, With Python Code

Base64 encoding turns bytes into 64 safe text characters. See the bit-level steps, padding, URL-safe base64, the 33% size cost,…

Read article →
DevOps

Git Tag: Create, Push and Delete Release Tags

Git tag explained with tested commands: annotated vs lightweight tags, listing and sorting, pushing with follow-tags, deleting local and remote…

Read article →
Test Automation

Pytest Coverage: pytest-cov and Branch Gaps

Measure pytest coverage with pytest-cov: term-missing reports, branch coverage, HTML reports, pyproject settings and a fail-under gate for CI, with…

Read article →
Software Testing

Error Guessing in Testing: Checklist + Demo

Error guessing uses tester experience to predict where code breaks. Get a ready checklist of risky inputs, a step by…

Read article →
Databases & SQL

SQL LAG and LEAD: Compare Rows, 5 Examples

SQL LAG and LEAD read values from the previous or next row without a self join. Five tested examples: change,…

Read article →
Databases & SQL

SQL STRING_AGG: Combine Rows Into One String

SQL STRING_AGG joins values from many rows into one string per group. See syntax for PostgreSQL, SQL Server, MySQL GROUP_CONCAT,…

Read article →
Software Development

JavaScript Classes: Private Fields and Extends

JavaScript classes explained with tested Node.js code: constructors, methods, #private fields, getters, static members, extends and super, plus the errors…

Read article →
Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →