Papa Programmer
Lesson 06 of 15

Keyword search and BM25

9 min read

Optional

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.

  1. Term frequency. A passage that uses the word more often scores higher, with diminishing returns. Ten mentions are not ten times better than one.
  2. Inverse document frequency. The fewer passages contain a word, the more that word is worth. The name is usually shortened to idf.
  3. 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.

python
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:

text
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 returns passage also contains the word, yet sale and shipping rank 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 for returns, 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 searchSemantic search
Exact names and codesFinds XR-500 at onceMay miss it
Different wording"Refund" does not match "money back"Finds both
CostVery fast, no model neededNeeds an embedding model
Explaining a resultThe matching words are the reasonHard to explain
Keyword search and semantic search side by side

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.

Rare words carry the signalBM25 gives a word more weight when fewer passages contain it.
Look up, don't scanAn inverted index maps each word to the passages that hold it.
Words, not meaning"Refund" will not find "money back". Embeddings can.

Your reading position is saved

0%

0 of 15 complete

Contents

Learning tools