Keyword search and BM25
9 min read
Matching words, but not all words equally
The earlier Lessons counted shared words. That treats every word as equally useful, and it is not. In a question about a bike warranty, the word "the" appears in nearly every passage and tells you nothing. The word "warranty" appears in one passage and tells you nearly everything.
BM25, short for Best Matching 25, is a formula that captures this. It is the standard keyword scoring method, and it has been in search engines for decades. It uses three ideas.
- Term frequency. A passage that uses the word more often scores higher, with diminishing returns. Ten mentions are not ten times better than one.
- Inverse document frequency. The fewer passages contain a word, the more that word is worth. The name is usually shortened to idf.
- Length normalisation. A short passage that contains the word is a closer match than a long one that mentions it in passing.
The index behind it
Searching every passage for every question is slow. Keyword search instead builds an Inverted indexA table that lists, for each word, the passages that contain it. A keyword search looks up the query's words in the table instead of reading every passage. once: a table that lists, for each word, the passages that contain it. A question is answered by looking up its few words in the table instead of reading every passage. This is the same idea as the index at the back of a book.
BM25 in a short program
The program below implements the formula with only the standard library. It prints the idf of three words first, and then ranks the passages for four queries.
import math
from collections import Counter
docs = {
"returns": "return an unused bike within 30 days for a refund",
"sale": "sale items can be returned within 14 days",
"warranty": "the frame has a 5 year warranty and the battery has a 2 year warranty",
"shipping": "standard shipping takes 3 to 5 business days",
"tyres": "bike tyres wear out so a bike needs new tyres every year",
}
tokens = {name: text.split() for name, text in docs.items()}
total = len(tokens)
average = sum(len(words) for words in tokens.values()) / total
document_frequency = Counter(word for words in tokens.values() for word in set(words))
def idf(word):
n = document_frequency[word]
return math.log(1 + (total - n + 0.5) / (n + 0.5))
def bm25(query, name, k1=1.5, b=0.75):
counts = Counter(tokens[name])
length = len(tokens[name])
score = 0.0
for word in query.split():
f = counts[word]
score += idf(word) * f * (k1 + 1) / (f + k1 * (1 - b + b * length / average))
return score
for word in ("days", "bike", "warranty"):
print(f"{word:<9} appears in {document_frequency[word]} documents, idf {idf(word):.2f}")
for query in ("days", "warranty", "return bike", "returned"):
ranked = sorted(tokens, key=lambda name: -bm25(query, name))[:2]
print(f"{query!r:<14}", [(name, round(bm25(query, name), 2)) for name in ranked])It prints:
days appears in 3 documents, idf 0.54
bike appears in 2 documents, idf 0.88
warranty appears in 1 documents, idf 1.39
'days' [('sale', 0.61), ('shipping', 0.61)]
'warranty' [('warranty', 1.75), ('returns', 0.0)]
'return bike' [('returns', 2.32), ('tyres', 1.2)]
'returned' [('sale', 1.56), ('returns', 0.0)]Read the output in three parts.
- Rare words weigh more. "warranty" appears in one passage and has an idf of 1.39. "days" appears in three and has 0.54.
- Length normalisation works. For the query "days", the
returnspassage also contains the word, yetsaleandshippingrank above it. They are shorter, so the word makes up more of them. - Exact words only. The query "returned" finds
sale, which contains "returned", and scores 0.0 forreturns, which contains "return". To BM25 these are different words.
k1 and b are two settings. k1 controls how fast repeated words stop adding score. b controls how strongly length is penalised. The values 1.5 and 0.75 used here are common defaults, and most systems keep them unless tests show a gain.
Where keyword search is strong
| Keyword search | Semantic search | |
|---|---|---|
| Exact names and codes | Finds XR-500 at once | May miss it |
| Different wording | "Refund" does not match "money back" | Finds both |
| Cost | Very fast, no model needed | Needs an embedding model |
| Explaining a result | The matching words are the reason | Hard to explain |
Keyword search is the right tool for names, codes, rare technical terms and anything the user types exactly as it appears in the document. It is the wrong tool when a user describes what they want in their own words. A common fix is a light clean-up of the words before indexing, such as lower-casing and stemming, which cuts "returned" and "returning" back to "return". It helps, but it cannot connect "refund" to "money back".
That gap is what embeddings fill, and the next Lesson, Embeddings and semantic search, shows how. Most strong systems then use both, which the Lesson Hybrid search and reranking explains.
A tool you can use today
You rarely write BM25 yourself. SQLite's built-in full-text search, Elasticsearch, OpenSearch and the open-source Python package rank_bm25 all provide it. The Stanford book Introduction to Information Retrieval explains the theory in depth.
Why does a rare word count for more in BM25?
'warranty' appears in one passage and 'days' in three.
This is inverse document frequency. A word found everywhere says little.
What does BM25 miss?
A user searches for 'money back' and the document says 'refund'.
BM25 matches words, not meaning. Embeddings can connect the two phrases.
What does an inverted index store?
A search engine must answer quickly across thousands of passages.
It works like the index at the back of a book, so a query is a lookup instead of a scan.
Your reading position is saved
0 of 15 complete
Lesson complete
Keyword search and BM25
Up next