06.7 Keyword Search and BM25
Lesson 02.3 ended with a warning: embeddings compress a text into a few hundred numbers that capture its gist, and precise details — exact identifiers, error codes, rare terms, numbers — often don't survive the compression. This lesson is about the retrieval method that never had that problem: keyword search, and specifically BM25, the ranking function that has been the backbone of search engines for thirty years and is still the strongest cheap baseline in 2026. You will build an inverted index from scratch, implement BM25 in pure Python, run real BM25 inside SQLite, and survey every production tool — from rank_bm25 to Elasticsearch, PostgreSQL full-text search, ParadeDB, VectorChord, Meilisearch and learned sparse models like SPLADE and BGE-M3. It stops where combination begins: how to merge lexical and dense results is lesson 06.8.
What you'll learn
- Why keyword search still matters in 2026, and exactly where dense retrieval fails — with worked examples from a running document corpus
- The inverted index: what it stores, how to build one in ~30 lines of pure Python, and what a real one looks like
- Analysis for search: tokenization, case folding, Unicode normalization, stopwords, stemming vs lemmatization, n-grams, code and identifier handling, and languages without spaces
- TF-IDF → BM25: term-frequency saturation, inverse document frequency, length normalization, the formula in code, a hand-computed 5-document example, tuning
k1andb, and the BM25+, BM25L and BM25F variants - Every production path to BM25: Python libraries (
rank_bm25,bm25s), SQLite FTS5 (with a complete runnable demo), PostgreSQL full-text search and its BM25 extensions (ParadeDBpg_search, VectorChord-BM25), the Lucene family (Elasticsearch, OpenSearch, Pyserini, tantivy, Whoosh), and typo-tolerant engines (Meilisearch, Typesense) - Query handling: query languages (phrases, boolean, prefix, NEAR, column filters), turning natural-language questions into keyword queries, synonyms and acronyms, typos and fuzzy matching, and keeping user input out of the query parser
- Field weighting: BM25F, per-column weights, and how title-vs-body boosting works in real engines
- Learned sparse retrieval: SPLADE-style and BGE-M3 sparse vectors as "BM25 with a neural net", and why they feed into hybrid search
- Scale and operations: index size, updates and segment merges, refresh latency, sharding, analyser-change reindexing, IDF drift, multilingual indexes, and cost arithmetic
- How to use BM25 as the baseline every retrieval experiment needs — and the traps that make lexical search silently wrong
What you don't need
- Any API keys, servers or databases. The core of this lesson runs on pure Python and Python's built-in
sqlite3. Engine samples (Elasticsearch, PostgreSQL, Meilisearch) are written against official documentation and labelled illustrative. - Vector search knowledge. If embeddings are new to you, start with lesson 02.3; this lesson is self-contained for the lexical side.
- A search-engine background. If you've used SQL
LIKE, Lucene or grep before, the 🔁 notes map the concepts.
Setup
The runnable parts need only Python 3.11+ (standard library — re, math, sqlite3). First time? Create a project with uv init keyword-search --bare --python 3.13 && cd keyword-search, then run scripts with uv run python file.py. See lesson 03.1, Part 4 for the full setup.
The library samples use these packages. The commands install the newest release of each; the samples were checked against rank_bm25 0.2.2 and bm25s 0.3.16 as of November 2026, and a newer version may change names or defaults, so check the library's changelog if a sample does not match:
uv add numpy rank_bm25 bm25s
# or: pip install numpy rank_bm25 bm25sNo .env file is needed: nothing in this lesson calls a hosted API.
What you must be able to do after this lesson#
- Explain how an inverted index and text analysis work
- Compute BM25 scores and explain each term
- Run BM25 with a production tool
- Handle query text such as phrases and typos
- Evaluate BM25 on your own data
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "BM25 is just an old algorithm — embeddings replaced it." | Part 1 |
| "Why did the assistant miss the error code E-4012?" | 1.1 What dense retrieval misses |
| "The inverted index is just a hash map of words." | 2.1 Build an inverted index |
| "Why does 'running' match 'run' but 'university' not match 'universe'?" | 2.4 Stemming vs lemmatization |
"What are k1 and b?" |
3.6 The parameters k1 and b |
| "BM25F? BM25+? BM25L? Which one does Elasticsearch use?" | 3.7 Variants |
| "Why does FTS5 return negative scores?" | 4.2 SQLite FTS5 |
"ts_rank isn't BM25?" |
4.3 PostgreSQL full-text search |
| "The user typed a quote and the search crashed." | 5.4 Keeping user input out of trouble |
| "How do I make the title count more than the body?" | Part 6: Field weighting |
| "SPLADE gives me BM25 for free?" | 4.6 Learned sparse retrieval |
| "Our help-centre search feels stale after every deploy." | 7.3 Refresh latency and near-real-time search |
Part 1: Why keyword search still matters#
1.1 What dense retrieval misses#
Lesson 02.3, 10.6 showed the failure modes of embedding-based retrieval with a small experiment: "has diabetes" vs "does not have diabetes" scored nearly the same as a true paraphrase, "3pm on 12 March" vs "9am on 21 March" scored 0.88, and "error code E-4012" vs "error code E-4021" scored 0.79 — almost as similar as a paraphrase. Embeddings capture topic and gist. They are deliberately fuzzy about the things keyword search is exact about:
| What users actually type or need | Why dense retrieval struggles | What keyword search does |
|---|---|---|
Exact identifiers: SKUs (SKU-4482), ticket IDs, part numbers |
Similar-looking strings embed nearby; the model can't tell E-4012 from E-4021 | Exact term match; E-4012 hits only documents containing it |
Error codes and log lines: ERR_CONNECTION_RESET, stack traces |
Rare tokens get poor vectors; punctuation is stripped by tokenizers | The token is indexed verbatim; substring/prefix queries find it |
Names: people, companies, products (ACME Corp) |
Names are sparse in training data; two similar names embed close | String match is exact |
Numbers, dates, prices, versions: $75, v2.4.1, 2026-03-12 |
Numbers tokenize weakly; "12" and "21" are both "a number" | Exact match; range/filter handled by metadata (06.6) |
Rare jargon and acronyms: idempotency, SLA, PII |
Rare terms get vague vectors | Indexed as-is; IDF makes rare terms more valuable, not less |
| Negation and precise wording: "does NOT include", "except on weekends" | One small word barely moves the vector | The word is a term like any other |
| Very short queries: "E-4012", "warranty?", "ACME" | Little context for the embedding to work with | Short queries are BM25's home turf |
The honest summary: dense retrieval wins on paraphrase and conceptual queries ("how do I get my money back?" should find the Returns article even though it never says "refund"); lexical retrieval wins on anything where the exact surface form matters. Production systems use both — that combination is lesson 06.8. This lesson makes you fluent in the lexical half.
1.2 What BM25 is good at — a comparison on the running corpus#
The module's running example is a fictional company "Acme" document set: a product handbook, a help centre, support tickets and contracts — the same corpus Module 05 builds chunks from. Here is a slice of it:
| Doc ID | Source | Title | gist |
|---|---|---|---|
handbook-warranty |
handbook | Warranty | 12-month warranty, defects covered, exclusions |
handbook-returns |
handbook | Returns | 30-day returns, refunds, non-refundable licences |
help-error-e4012 |
help | Error E-4012 at checkout | payment gateway timeout, retry, transaction ID |
ticket-1042 |
ticket | Checkout fails for card payments | reproduces E-4012, Chrome, TXN-8841 |
contract-liability |
contract | Liability | liability cap, consequential damages |
Now compare what each retriever does with five realistic queries:
| Query | Dense (embeddings) likely returns | BM25 returns | Winner and why |
|---|---|---|---|
| "what's the error code for checkout timeouts?" | help-error-e4012, ticket-1042 (conceptual match works well) | Same two docs — "checkout", "timeout"/"timed out" match | Tie; dense is more forgiving of phrasing |
| "E-4012" | Possibly the right docs, possibly other checkout docs — the vector for "E-4012" is nearly identical to "E-4021" | Exactly the docs containing the literal token 4012 |
BM25, decisively |
| "what happens if I return an opened licence?" | handbook-returns (paraphrase match) | handbook-returns — "return", "licence" appear; "opened" too | Dense slightly better on phrasing; BM25 still fine |
| "TXN-8841" | Arbitrary — one rare token in a sea of "checkout/payment" context | Exactly ticket-1042 | BM25, decisively |
| "does the warranty cover water damage?" | handbook-warranty (topic match) | handbook-warranty — "warranty", "damage" match | Tie on retrieval; the answer still needs the LLM (Module 07) |
1.3 The BM25 pipeline#
Every keyword search system — SQLite, Elasticsearch, your own Python — is the same five stages:
flowchart LR
subgraph index ["Indexing (once per document)"]
D["document text"] --> A["analyser:<br/>lowercase, fold, tokenize, stem"]
A --> T["terms"]
T --> II["inverted index:<br/>term → postings(doc, tf, positions)"]
end
subgraph query ["Query time (per search)"]
Q["query text"] --> QA["same analyser"]
QA --> QT["query terms"]
QT --> PL["postings lookup"]
PL --> SC["BM25 score per doc"]
SC --> TOP["top-k results"]
end
II --> PLTwo things to notice. First, the same analyser must run on documents and queries — if the index stores warranty but the query analyser produces warranti, nothing matches (we'll hit this failure in 2.8). Second, BM25 is only the last box. Everything before it — analysis, the inverted index, postings — is shared infrastructure with every other keyword engine, which is why learning it once transfers everywhere.
Part 2: The inverted index and analysis#
2.1 Build an inverted index in about 30 lines#
Here is a complete, runnable implementation. Our toy analyser is deliberately minimal: lowercase, then extract [a-z0-9]+ tokens. Production analysers do much more (2.3–2.7) — the point is to see the shape of the data structure.
# inv_index.py — a minimal inverted index, standard library only
import re
from collections import defaultdict
TOKEN_RE = re.compile(r"[a-z0-9]+")
def tokenize(text: str) -> list[str]:
return TOKEN_RE.findall(text.lower())
# Five short documents about returns/refunds (tokenized for us)
docs = [
"damaged refund policy proof purchase receipt",
"package arrived damaged request refund",
"shipping times delivery estimates express standard",
"damaged goods shipping delay complaint refund",
"password reset link expires fifteen minutes",
]
# postings[term][doc_id] = list of token positions where the term occurs
postings: dict[str, dict[int, list[int]]] = defaultdict(lambda: defaultdict(list))
doc_len = []
for i, text in enumerate(docs):
tokens = tokenize(text)
doc_len.append(len(tokens))
for pos, term in enumerate(tokens):
postings[term][i].append(pos)
avgdl = sum(doc_len) / len(doc_len) # average document length, in tokens
print("doc lengths:", doc_len, "avgdl:", round(avgdl, 3))
for term in ["damaged", "refund", "shipping", "e-4012", "reset"]:
print(f" {term!r}: df={len(postings.get(term, {}))} -> {dict(postings.get(term, {}))}")doc lengths: [6, 5, 6, 6, 6] avgdl: 5.8
'damaged': df=3 -> {0: [0], 1: [2], 3: [0]}
'refund': df=3 -> {0: [1], 1: [4], 3: [5]}
'shipping': df=2 -> {2: [0], 3: [2]}
'e-4012': df=0 -> {}
'reset': df=1 -> {4: [1]}Read that output carefully — it is the whole concept:
postings['damaged']maps document index → positions: doc 0 has "damaged" at position 0, doc 1 at position 2, doc 3 at position 0. Three documents → document frequency (df) = 3.'e-4012'produced df=0 — our regex split it intoeand4012(hyphens are separators). This is not a bug; it's the first hint that how you tokenize decides what is searchable (2.6).doc_lenandavgdlare stored because BM25 needs them for length normalization (3.3).
What this costs: the index is roughly proportional to total tokens — for a corpus of N docs averaging L tokens, you store ~N×L posting entries plus per-term overhead. For 100k help articles averaging 300 tokens that's ~30M postings — comfortably in RAM for a modern server, and the reason keyword search scales to billions of documents in engines like Elasticsearch. We'll do the arithmetic properly in 7.1.
2.2 Analysis for search is not tokenization for LLMs#
Lesson 02.2 taught that LLMs read subword tokens produced by BPE — unbelievable might be un + believ + able, and E-4012 becomes several tokens whose meaning the model infers from context. Search analysis is a different pipeline with a different goal: produce a canonical string per term so that variants of the same word collapse to one index entry, and different words stay distinct.
| LLM tokenization (02.2) | Search analysis | |
|---|---|---|
| Goal | Feed the model a sequence it can predict over | Canonicalize text so variants match exactly |
| Granularity | Subwords; rare words split into pieces | Usually whole words after stemming; sometimes n-grams |
| Case | Often preserved or normalized per model | Almost always folded to lowercase |
| Punctuation | Kept as tokens where meaningful | Usually stripped as separators |
| Output | Token IDs into an embedding table | Strings (or term IDs) into an inverted index |
| Stemming | Never — the model learns morphology itself | Frequently — running/runs/ran may share a stem |
| Examples | o200k_base, SentencePiece, tiktoken |
Lucene StandardAnalyzer, Elasticsearch analysers, FTS5 tokenizers |
A search analyser (American spelling in the APIs; "analyser" in British prose) is a configurable pipeline of components. In Elasticsearch/Lucene terms it is: char filters → tokenizer → token filters. In SQLite FTS5 you pick a tokenizer (unicode61, porter, trigram, ascii) which bundles several of those steps. In PostgreSQL the equivalent is the text search configuration (to_tsvector('english', ...)) — a dictionary plus stemmer plus stopword list per language.
The components, in pipeline order:
- Char filters — rewrite the raw string before tokenizing: HTML tag stripping, ASCII folding (
café→cafe), pattern replacement (e.g.→for example). - Tokenizer — split text into candidate tokens: whitespace/punctuation rules, or word segmentation for languages without spaces.
- Token filters — transform each token: lowercase, strip diacritics, stopword removal, stemming/lemmatization, synonym expansion, n-gram generation, length limits.
Every choice is a trade-off, and the trade-off is always the same shape: recall (find more potentially relevant docs) vs precision (don't match things that aren't the same word) vs index size/speed.
2.3 Case folding, Unicode and stopwords#
Case folding. Almost every analyser lowercases. "Warranty" and "warranty" must hit the same postings or search feels randomly broken — and the breakage is silent: the query returns nothing and no error is raised. Case folding is subtler than .lower() in Unicode (Turkish dotless i, German ß→ss), which is why engines ship tuned analysers rather than asking you to roll your own.
Unicode normalization and diacritics. café, cafe, and café typed on different keyboards should usually match. Most analysers apply NFKD-style decomposition plus diacritic removal for Latin script. SQLite's unicode61 tokenizer does exactly this by default — its docs note that "diacritics are removed from all Latin script characters", so é, è, ê fold to e. The cost: you can no longer distinguish resume (CV) from résumé if your corpus cares — rare, but real for legal/name search. Keep a keyword-type field (un-analysed) alongside the analysed one when exactness matters.
Stopwords. Words like "the", "is", "a", "of" appear in nearly every document. They contribute almost no discriminating power but inflate index size and can dominate phrase/proximity scoring. Most analysers remove a stopword list — but it's a trade-off, not a free win:
- Removing stopwords shrinks the index and prevents "the" from matching everything.
- But it breaks phrase queries:
"to be or not to be"becomes"be not"— and it destroys meaningful distinctions in some domains (legal phrases, poetry, code comments where "not"/"no" carry the meaning). - BM25's IDF already handles common words gracefully: a term in 90% of documents gets near-zero or negative weight, so stopword removal is less critical for ranking than for index size and phrase correctness.
2.4 Stemming vs lemmatization#
Users type warranty, warranties, warranted; documents contain all three. Stemming crudely chops word endings to a common root using rules; lemmatization uses a real dictionary to find the base form ("better"→"good", "ran"→"run", "geese"→"goose").
| Stemming (e.g. Porter) | Lemmatization (e.g. WordNet) | |
|---|---|---|
| Method | Suffix-stripping rules, no dictionary | Dictionary + morphology analysis |
| Speed | Very fast | Slower (lookups) |
| "running", "runs", "run" | usually → run |
→ run |
| "better" | → better (unchanged!) |
→ good |
| "university" vs "universe" | can over-stem to univers — collision |
stays distinct |
| "policies" vs "policy" | → polici both |
→ policy/policies handled properly |
| Used in | Lucene PorterStemFilter, FTS5 porter tokenizer, Elasticsearch stemmer token filter |
Elasticsearch stemmer with keyword-aware setups, spaCy/NLTK pipelines, bm25s optional PyStemmer |
The classic Porter stemmer (1980) is what most engines ship. Its quirks are legendary: university→univers, news→news (fine), relational→relat, ponies→poni. Over-stemming collisions merge distinct words (university/universe, organization/organ) — acceptable for recall-oriented first-stage retrieval because a reranker or the LLM sorts out the noise later, but it can also merge terms you needed distinct.
The practical rule: stem for recall at index time, keep an unstemmed keyword field for exact matching, and evaluate on your own queries whether stemming helps — 06.10 exists precisely for this.
2.5 N-grams, edge n-grams, wildcards and fuzzy matching#
N-grams index every contiguous character sequence of length n (typically 3) instead of whole words — the trigram tokenizer in SQLite FTS5, edge_ngram/ngram token filters in Lucene. Why? They make substring matching work: searching passw finds password, passage finds passage inside bypassage, and — crucially — they give you typo tolerance and prefix matching without scanning the dictionary. Cost: index size grows (every 3-char window of every word), and scores get fuzzier.
Wildcards and prefixes (ship*, warran*) are the query-side version: match any indexed term with the given prefix. They need a prefix index to be fast — SQLite FTS5 supports prefix='2 3' options that build extra indexes for 2- and 3-character prefixes; without it, prefix queries range-scan the term dictionary (fine at small scale, slow at millions of terms). Lucene does the same with WildcardQuery/PrefixQuery and its terms index.
Fuzzy matching goes further: warrenty~ should match warranty within edit distance 1. Engines implement this with Levenshtein automata — a finite-state machine that walks the term dictionary and accepts only terms within the allowed edit distance (this is exactly what Meilisearch does with its FST, per its docs). Lucene has FuzzyQuery; Elasticsearch exposes it as the fuzziness parameter (AUTO = edit distance scaled by term length). We'll cover query-side typos in 5.3.
2.6 Code, identifiers, numbers and units#
This is where generic analysers quietly lose. Real corpora are full of things that aren't prose:
| Text | Naive [a-z]+ analysis |
What you probably want |
|---|---|---|
E-4012, TXN-8841, SKU-4482 |
e, txn, sku, 4012, 8841, 4482 — the meaningful part survives but the prefix is junk; E-4012 vs E-4021 differ only in 4012/4021 |
Index the whole identifier as one term (custom tokenizer/char filter keeping - and _), or accept the split and rely on 4012 matching — both work, the first is cleaner |
camelCase, snake_case, kebab-case identifiers |
camelcase, snake, case, kebab, case — loses the word boundaries the author chose |
Edge-ngram or a tokenizer that splits on case transitions (camelCaseFilter-style); at minimum know that getUserById becomes one blob to a naive analyser |
v2.4.1, 3.11, 2026-03-12, $75, 50% |
v2, 4, 1, 3, 11, 2026, 03, 12, 75, 50 — version/date fragments that match everything numerically similar |
Keep versions/dates/amounts as metadata fields and filter on them exactly (06.6); optionally index normalized forms (v2.4.1→v2_4_1) |
C++, C#, Node.js, don't |
c, node, js, don, t — punctuation destroys the term |
Custom char filters or keyword fields; English possessives usually want don't→don t or dont handled deliberately |
12-month, 3-5 days, $50 |
12, month, 3, 5, days, 50 |
Acceptable for prose; for spec-like text consider keeping hyphenated units intact |
| Units and currencies | 75 matches 75 anywhere — $75 vs 75kg vs 75% indistinguishable |
Again: metadata for anything you filter or boost on |
2.7 Languages without spaces: CJK and beyond#
English, Spanish, German: words are separated by spaces, so whitespace tokenization mostly works. Chinese, Japanese, Thai, Khmer, Lao and Burmese don't use spaces between words — "我想退货" is one string containing multiple words ("I want to return goods"). A whitespace tokenizer indexes the entire sentence as one giant term; nothing ever matches.
The solutions, in increasing sophistication:
- Dictionary/segmenter tokenizers — Lucene's
SmartChineseAnalyzer(dictionary-based),JapaneseTokenizer/Kuromoji(morphological),ThaiTokenizer; Elasticsearch bundlesanalysis-icuandanalysis-kuromojiplugins; PostgreSQL haszhparser/pg_jiebaextensions; SQLite has no built-in CJK segmenter (you'd preprocess or use a custom tokenizer — FTS5 supports custom tokenizers in C). - Character n-grams — index overlapping character bigrams/trigrams; crude but language-agnostic and surprisingly effective for CJK retrieval (this is what many production CJK search setups do).
- Language detection + per-field analysers — route each document to the analyser for its detected language; Elasticsearch's
matchquery accepts a per-field or per-index analyser, andmulti-fieldslet you index the same text under several analysers.
Also relevant: morphologically rich languages (Finnish, Turkish, Hungarian) produce many word forms; stemming helps but isn't enough — lemmatization or n-gram fallback may be needed. And mixed-language corpora (English docs with Japanese product names) need per-field or per-term handling. If your corpus is >10% non-Latin-script, test retrieval per language before shipping — averages hide per-language failures.
2.8 The analyser-mismatch failure#
The single most common lexical-search bug in production:
- Index built with
porterstemming + stopword removal. - Query path uses a different analyser — a different tokenizer, no stemming, or a hand-rolled
.lower().split(). - Result:
runningin the index is stored asrun; the query analyser producesrunning; zero results, no error.
Every engine guards against this differently: Elasticsearch requires you to think about index vs search analyser (they can differ deliberately); FTS5 binds the tokenizer at CREATE VIRTUAL TABLE time so index and query share it by construction (but you can still shoot yourself with external-content tables or by querying with raw strings that bypass analysis); PostgreSQL lets you choose a config per to_tsvector/to_tsquery call — mismatched configs are a classic bug (to_tsvector('english', ...) vs to_tsquery('simple', ...)).
Rule: the analyser is part of your index format version. Changing it means reindexing everything (7.5). Record it in metadata next to your chunk IDs (05.8) exactly like you record the embedding model.
Part 3: From TF-IDF to BM25#
3.1 The problem with raw term frequency#
The naive scoring idea: count how often each query term appears in a document and sum. A document mentioning "warranty" 10 times should outrank one mentioning it once, right? Mostly — until you look at what raw counts do:
- A 5,000-word legal contract that mentions "damages" twice scores the same as a 50-word FAQ that mentions it twice — but the FAQ is almost certainly the better answer.
- A document that repeats "refund refund refund refund" (spam, SEO stuffing, or just a repetitive template) wins unfairly.
- Duplicated boilerplate ("click here to unsubscribe" in every email) inflates scores for terms nobody searched for.
So term frequency needs saturation: the jump from 1→2 occurrences matters a lot; the jump from 20→21 barely matters at all. And it needs length normalization: longer documents have more chances to contain any term by accident.
3.2 Inverse document frequency#
Some terms are everywhere ("the", "error", "please"); others are rare ("E-4012", "idempotency"). A term's value should be inverse to how many documents contain it — that's document frequency (df), and inverse document frequency (IDF) converts it into a weight. The Robertson IDF used by Lucene/Elasticsearch and most modern implementations:
idf(term) = ln( 1 + (N - df + 0.5) / (df + 0.5) )where N is the total number of documents. The +1 inside the log guarantees IDF is always positive; Robertson's original formulation without it (ln((N-df+0.5)/(df+0.5))) goes negative for terms appearing in more than half the corpus — which is why rank_bm25 ships an epsilon floor. (SQLite FTS5's negative scores are a separate matter: it returns the negated BM25 so that an ascending ORDER BY puts the best match first — 4.2.) Rare terms get large positive IDF; ubiquitous terms approach 0.
Quick feel for it on our 5-doc corpus: damaged has df=3 of N=5 → idf = ln(1 + 2.5/3.5) ≈ 0.54. shipping has df=2 → idf ≈ 0.88. reset has df=1 → idf ≈ 1.39. Rare terms dominate scoring — which is exactly what you want: matching "E-4012" should matter far more than matching "the".
3.3 Document-length normalization#
A document twice the average length contains roughly twice as many term occurrences by chance. BM25 normalizes each document's effective length against the corpus average avgdl, controlled by parameter b ∈ [0,1]: b=0 ignores length entirely; b=1 fully normalizes (a document twice avgdl needs twice the tf for the same score). The classic default b=0.75 — long documents are penalized, but not brutally. (Classic TF-IDF variants bolt on length normalisation too — cosine or pivoted — but the canonical tf × idf of 3.4 has none; BM25 builds it into the formula.)
3.4 TF-IDF: tf × idf — the score BM25 replaces#
Before BM25 there was TF-IDF — the workhorse of information retrieval from the 1970s through the 2000s, and still what scikit-learn's TfidfVectorizer computes by default. Strip it to essentials: score each query term by term frequency × inverse document frequency and sum across query terms:
tfidf(t, D) = tf(t, D) × idf(t)
score(D, Q) = Σ over query terms t of tfidf(t, D)Same ingredients we just met — raw tf, Robertson-style idf — with none of BM25's refinements. On the same 5-document corpus:
# tfidf_toy.py — tf x idf on the same 5 documents (stdlib only)
import math
import re
from collections import Counter
TOKEN_RE = re.compile(r"[a-z0-9]+")
def tokenize(text: str) -> list[str]:
return TOKEN_RE.findall(text.lower())
docs = [
"damaged refund policy proof purchase receipt",
"package arrived damaged request refund",
"shipping times delivery estimates express standard",
"damaged goods shipping delay complaint refund",
"password reset link expires fifteen minutes",
]
tok = [tokenize(d) for d in docs]
N = len(tok)
df = Counter()
for ts in tok:
df.update(set(ts)) # document frequency
def idf(term: str) -> float:
n = df.get(term, 0) # Robertson+1, same as §3.5's BM25
return math.log(1 + (N - n + 0.5) / (n + 0.5)) if n else 0.0
def tfidf(query: str) -> list[float]:
counts = [Counter(ts) for ts in tok]
return [sum(c[t] * idf(t) for t in tokenize(query)) for c in counts]
print("TF-IDF 'damaged refund':", [round(s, 4) for s in tfidf("damaged refund")])
# a doc repeating 'damaged' 5x scores 5 x idf = 2.69 — tf is linear, no saturationTF-IDF 'damaged refund': [1.078, 1.078, 0.0, 1.078, 0.0]Two things to notice, because they are exactly what BM25 fixes:
- Docs 1, 2 and 4 tie at 1.078 (= idf(damaged) + idf(refund) = 0.539 + 0.539). Classic TF-IDF ignores document length entirely — doc2's 5 tokens and doc1's 6 tokens score identically, and a 5,000-word contract would score the same as a 50-word FAQ. (Some TF-IDF variants bolt on length normalisation — cosine or pivoted — but the canonical form doesn't have it.)
tfis linear: a document repeating "damaged" five times scores5 × 0.539 = 2.69— term stuffing wins outright. There is no saturation.
So the "from" in this part's title is literal: BM25 keeps TF-IDF's tf × idf skeleton and replaces both weak ingredients — saturating the term frequency and building length normalisation in.
| TF-IDF | BM25 | |
|---|---|---|
| Term frequency | linear tf — 5 occurrences score 5× |
saturated tf(k1+1)/(tf + k1·norm) — 5 occurrences score ~1.8× |
| Document length | ignored by the canonical form | built in via b and avgdl |
| IDF | same family; several historical variants (some go negative) | Robertson+1 / ATIRE / BM25L / BM25+ depending on implementation |
Our corpus, query damaged refund |
docs 1, 2, 4 tie at 1.078 | doc2 wins 1.1425 vs 1.063 (§3.5) |
3.5 The BM25 formula, in code#
Putting it together — Okapi BM25, the variant used by Lucene, Elasticsearch, OpenSearch, SQLite FTS5, rank_bm25's BM25Okapi and bm25s's lucene/robertson methods:
score(D, Q) = Σ over query terms t of:
idf(t) × tf(t,D)·(k1+1) / ( tf(t,D) + k1·(1 − b + b·|D|/avgdl) )with the usual defaults k1=1.2, b=0.75 (Robertson & Zaragoza's recommended values; Elasticsearch's BM25Similarity defaults, verified on the current docs). k1 controls term-frequency saturation: k1→0 makes tf binary (present/absent), k1→∞ makes tf nearly linear.
Here is a complete from-scratch implementation — about 50 lines, standard library only:
# bm25_toy.py — Okapi BM25 from scratch
import math
import re
from collections import defaultdict
TOKEN_RE = re.compile(r"[a-z0-9]+")
def tokenize(text: str) -> list[str]:
return TOKEN_RE.findall(text.lower())
class BM25:
"""Okapi BM25 with Robertson+1 IDF (the Lucene/Elasticsearch variant)."""
def __init__(self, docs_tokens: list[list[str]], k1: float = 1.2, b: float = 0.75):
self.k1, self.b = k1, b
self.N = len(docs_tokens)
# postings[term][doc_id] = positions; doc_len[i] = token count
self.postings: dict[str, dict[int, list[int]]] = defaultdict(lambda: defaultdict(list))
self.doc_len = []
for i, toks in enumerate(docs_tokens):
self.doc_len.append(len(toks))
for pos, t in enumerate(toks):
self.postings[t][i].append(pos)
self.avgdl = sum(self.doc_len) / self.N
self.df = {t: len(d) for t, d in self.postings.items()}
def idf(self, term: str) -> float:
n = self.df.get(term, 0)
return math.log(1 + (self.N - n + 0.5) / (n + 0.5)) if n else 0.0
def term_score(self, term: str, doc_id: int) -> float:
tf = len(self.postings.get(term, {}).get(doc_id, ()))
if tf == 0:
return 0.0
norm = 1 - self.b + self.b * self.doc_len[doc_id] / self.avgdl
return self.idf(term) * (tf * (self.k1 + 1)) / (tf + self.k1 * norm)
def search(self, query: str, k: int = 10) -> list[tuple[float, int]]:
q = tokenize(query)
scored = sorted(
((sum(self.term_score(t, i) for t in q), i) for i in range(self.N)),
key=lambda x: -x[0],
)
return [(s, i) for s, i in scored if s > 0][:k]
# --- the 5-document worked example ---
docs = [
"damaged refund policy proof purchase receipt",
"package arrived damaged request refund",
"shipping times delivery estimates express standard",
"damaged goods shipping delay complaint refund",
"password reset link expires fifteen minutes",
]
if __name__ == "__main__":
bm = BM25([tokenize(d) for d in docs])
print("=== BM25 scores for query 'damaged refund' (k1=1.2, b=0.75) ===")
for term in ["damaged", "refund"]:
print(f" idf({term}) = ln(1 + (5 - {bm.df[term]} + 0.5)/({bm.df[term]} + 0.5)) = {bm.idf(term):.6f}")
for i, d in enumerate(docs):
parts = {t: bm.term_score(t, i) for t in ["damaged", "refund"]}
print(f" doc{i+1} dl={bm.doc_len[i]}: " +
" + ".join(f"{t}={v:.6f}" for t, v in parts.items() if v) +
f" total={sum(parts.values()):.6f}")
print(" ranking:", [(i + 1, round(s, 4)) for s, i in bm.search("damaged refund")])=== BM25 scores for query 'damaged refund' (k1=1.2, b=0.75) ===
idf(damaged) = ln(1 + (5 - 3 + 0.5)/(3 + 0.5)) = 0.538997
idf(refund) = ln(1 + (5 - 3 + 0.5)/(3 + 0.5)) = 0.538997
doc1 dl=6: damaged=0.531499 + refund=0.531499 total=1.062998
doc2 dl=5: damaged=0.571229 + refund=0.571229 total=1.142458
doc3 dl=6: total=0.000000
doc4 dl=6: damaged=0.531499 + refund=0.531499 total=1.062998
doc5 dl=6: total=0.000000
ranking: [(2, 1.1425), (1, 1.063), (4, 1.063)]Walk through doc2 vs doc1: both contain each term once, but doc2 has 5 tokens vs doc1's 6, and avgdl is 5.8 — so doc2's length-normalization denominator is smaller, its tf contribution is larger (0.571 vs 0.531 per term), and it wins. Same term frequencies, different document lengths → different scores. That is length normalization doing its job. Docs 3 and 5 score 0 — no query terms, no match.
3.6 The parameters k1 and b#
| Parameter | Range | Effect of increasing | Classic default | What it really controls |
|---|---|---|---|---|
k1 |
≥ 0 | tf contribution saturates later — repeated terms keep adding score almost linearly | 1.2 (Lucene/ES/FTS5); rank_bm25 ships 1.5 | How much a term said 5 times beats said once |
b |
[0, 1] | stronger penalty for long documents | 0.75 | How much document length matters |
Two honest caveats. First, defaults are starting points, not truths — the IR literature tunes them per collection, and the differences on real corpora are usually small (a few nDCG points either way). Second, you will rarely tune them by hand: 06.10 sweeps them on your labelled query set. What you should internalize is the failure mode each prevents: b too low → long documents dominate; k1 too high → term stuffing wins.
Here's the saturation behaviour — score contribution of one query term as tf grows, computed with k1=1.2, b=0.75, avgdl=100 and idf held fixed at ≈2.26 (so the tf=1/norm=1.0 cell reads ~2.26):
dl= 50 norm=0.625 tf=1:2.846 tf=2:3.622 tf=4:4.194 tf=8:4.553
dl= 100 norm=1.000 tf=1:2.264 tf=2:3.113 tf=4:3.831 tf=8:4.331
dl= 200 norm=1.750 tf=1:1.607 tf=2:2.429 tf=4:3.266 tf=8:3.945Read it: going from tf=1 to tf=2 roughly doubles-ish the score (2.26→3.11); from tf=4 to tf=8 adds only ~0.5. Diminishing returns built in — that's saturation. And the same tf scores much higher in a short doc (dl=50) than a long one (dl=200): 2.85 vs 1.61 at tf=1.
And a sweep on a 10-document Acme corpus — the five §1.2 docs plus five more (expenses handbook, password help, warranty-ticket, liability and termination contracts). Top-1 result per query, real output:
| # | Doc ID | Title | gist |
|---|---|---|---|
| 1 | handbook-warranty |
Warranty | 12-month warranty, defects, proof of purchase |
| 2 | handbook-returns |
Returns | 30-day returns, refunds, free return shipping |
| 3 | handbook-shipping |
Shipping | 3–5 day delivery, express $12 |
| 4 | handbook-expenses |
Expenses | travel claims to $75/day, receipts over $25 |
| 5 | help-reset-password |
Reset your password | Settings → Security, link expires in 15 min |
| 6 | help-error-e4012 |
Error E-4012 at checkout | gateway timeout, retry once |
| 7 | ticket-1042 |
Checkout fails for card payments | E-4012 repro, TXN-8841 |
| 8 | ticket-1087 |
Cracked screen warranty claim | warranty denied, wants replacement |
| 9 | contract-liability |
Liability | liability cap, consequential damages excluded |
| 10 | contract-termination |
Termination | 30 days' notice, fees non-refundable |
# k1b_sweep.py — k1/b sweep; imports BM25 + tokenize from bm25_toy.py (§3.5)
from bm25_toy import BM25, tokenize
ACME = [
("handbook-warranty", "Warranty", "Products carry a 12-month warranty covering manufacturing defects. Claims require proof of purchase and the serial number. Damage from misuse or normal wear is excluded."),
("handbook-returns", "Returns", "Unopened products may be returned within 30 days for a full refund. Return shipping is free for manufacturing defects."),
("handbook-shipping", "Shipping", "Standard delivery takes 3-5 business days. Express delivery costs $12. Remote areas may take longer."),
("handbook-expenses", "Expenses", "Employees may claim travel expenses up to $75 per day. Receipts are required for claims over $25."),
("help-reset-password", "Reset your password", "Go to Settings then Security and choose Reset password. The reset link expires after 15 minutes."),
("help-error-e4012", "Error E-4012 at checkout", "Error E-4012 means the payment gateway timed out during checkout. Retry the payment once. If it persists, contact billing."),
("ticket-1042", "Checkout fails for card payments", "Customer reports checkout fails with error E-4012 on card payments. Transaction ID TXN-8841. Browser: Chrome."),
("ticket-1087", "Cracked screen warranty claim", "Customer bought a phone last month; the screen cracked and the warranty claim was denied. Asking for a replacement."),
("contract-liability", "Liability", "The supplier's total liability shall not exceed the fees paid in the preceding 12 months. Consequential damages are excluded."),
("contract-termination", "Termination", "Either party may terminate this agreement with 30 days written notice. Fees already paid are non-refundable."),
]
DOCS = [tokenize(t + " " + b) for _, t, b in ACME]
IDS = [d for d, _, _ in ACME]
for k1, b in [(0.5, 0.0), (0.5, 0.75), (1.2, 0.0), (1.2, 0.75),
(1.2, 1.0), (2.0, 0.75), (2.0, 1.0)]:
bm = BM25(DOCS, k1=k1, b=b)
tops = []
for q in ["damaged refund", "warranty screen", "checkout error"]:
hits = bm.search(q, k=1)
tops.append(f"{q!r}->{IDS[hits[0][1]]}({hits[0][0]:.3f})" if hits else f"{q!r}->none")
print(f" k1={k1} b={b}: " + " ".join(tops)) k1=0.5 b=0.0: 'damaged refund'->handbook-returns(1.992) 'warranty screen'->ticket-1087(4.169) 'checkout error'->help-error-e4012(3.556)
k1=0.5 b=0.75: 'damaged refund'->handbook-returns(2.016) 'warranty screen'->ticket-1087(4.110) 'checkout error'->help-error-e4012(3.457)
k1=1.2 b=0.0: 'damaged refund'->handbook-returns(1.992) 'warranty screen'->ticket-1087(4.777) 'checkout error'->help-error-e4012(4.074)
k1=1.2 b=0.75: 'damaged refund'->handbook-returns(2.032) 'warranty screen'->ticket-1087(4.652) 'checkout error'->help-error-e4012(3.867)
k1=1.2 b=1.0: 'damaged refund'->handbook-returns(2.046) 'warranty screen'->ticket-1087(4.612) 'checkout error'->help-error-e4012(3.803)
k1=2.0 b=0.75: 'damaged refund'->handbook-returns(2.041) 'warranty screen'->ticket-1087(5.031) 'checkout error'->help-error-e4012(4.148)
k1=2.0 b=1.0: 'damaged refund'->handbook-returns(2.058) 'warranty screen'->ticket-1087(4.974) 'checkout error'->help-error-e4012(4.058)Honest reading: across the whole grid the winners never change — only the scores drift. On 10 short, same-length-ish documents the corpus is too homogeneous for k1/b to matter. The parameters earn their keep on corpora with real length variance (a 20-word FAQ next to a 4,000-word contract) — which is why 06.10 sweeps them on a labelled query set instead of trusting defaults or toy data.
3.7 BM25 variants: BM25+, BM25L and BM25F#
The "Which BM25 do you mean?" problem is real: the literature has at least five named variants, and libraries implement different ones under the same name (Kamphuis et al., ECIR 2020, reproduced them all; bm25s exposes method="robertson" | "atire" | "bm25l" | "bm25+" | "lucene").
| Variant | Year / authors | The change | When it matters |
|---|---|---|---|
| Okapi BM25 | Robertson & Walker 1994; formalized Robertson & Zaragoza 2009 | The baseline above | Default everywhere |
| BM25F | Robertson, Zaragoza & Taylor 2004 | Scores multiple weighted fields (title, headings, body) with per-field length normalization, then saturates once | Structured documents — title vs body boosting; see Part 6 |
| BM25L | Lv & Zhai, SIGIR 2009 ("When documents are very long, BM25 fails") | Shifts the length-normalization curve so very long docs aren't over-penalized; adds parameter delta |
Corpora with extreme length variance |
| BM25+ | Lv & Zhai, CIKM 2011 | Adds a lower bound delta to each term's tf contribution, so a document containing the term can't score ~0 just for being long |
Same failure mode as BM25L, different fix |
| BM25-adpt / BM25T | Lv & Zhai 2012 / Trotman et al. | Term-specific k1 estimated from collection stats | Research-grade tuning; rarely shipped |
rank_bm25 0.2.2 implements BM25Okapi (k1=1.5 default — note, not 1.2), BM25L (delta=0.5) and BM25Plus (delta=1) with the same get_scores/get_top_n interface. bm25s implements five variants via method=. FTS5 hard-codes classic Okapi k1=1.2/b=0.75 — you can't change them without a custom auxiliary function. Practical advice: default BM25 almost everywhere; reach for BM25L/+ only when your eval set shows long-document misses; use BM25F-style field weighting constantly (Part 6).
Part 4: Production tools#
4.1 Python libraries: from-scratch, rank_bm25 and bm25s#
You now own the algorithm; the question is which implementation to use. Three honest tiers:
| Tool | What it is | Best for | Watch out for |
|---|---|---|---|
| Your own ~50 lines (above) | Pure Python, no deps | Learning, tiny corpora (<~50k docs), full control, tests | No persistence, no fancy query syntax, you maintain it |
rank_bm25 0.2.2 |
The classic Python lib (Apache-2.0, last release Feb 2022 — stable because BM25 doesn't change) | Quick prototypes, notebooks, small services | No preprocessing — you tokenize; BM25Okapi defaults k1=1.5 not 1.2; numpy dep; loads whole corpus in RAM |
bm25s 0.3.16 |
NumPy/SciPy sparse-matrix BM25 by Xing Han Lù (arXiv 2407.03618); claims orders-of-magnitude faster than rank_bm25 via "eager scoring" | Production-ish Python retrieval, saved/memory-mapped indexes, variant comparison | Younger project; simpler tokenizer than Lucene analysers; optional deps for stemming (PyStemmer) and JIT (numba) |
rank_bm25 usage (illustrative — needs uv add rank_bm25):
from rank_bm25 import BM25Okapi, BM25Plus
corpus = ["warranty covers defects for one year", "returns within 30 days",
"shipping takes 3-5 business days"]
tokenized = [doc.lower().split() for doc in corpus] # YOU preprocess
bm25 = BM25Okapi(tokenized) # k1=1.5, b=0.75 defaults
scores = bm25.get_scores("warranty".split())
top = bm25.get_top_n("warranty".split(), corpus, n=1) # returns doc strings
plus = BM25Plus(tokenized) # BM25+ variant, same APIscores: [0.47, 0.0, 0.0] top: ['warranty covers defects for one year']bm25s usage (illustrative — needs uv add bm25s; optional PyStemmer for stemming):
import bm25s
corpus = ["a cat is a feline and likes to purr",
"a dog is the human's best friend and loves to play",
"a bird is a beautiful animal that can fly"]
corpus_tokens = bm25s.tokenize(corpus, stopwords="en") # built-in tokenizer
retriever = bm25s.BM25(corpus=corpus)
retriever.index(corpus_tokens)
query_tokens = bm25s.tokenize("does the cat purr?")
docs, scores = retriever.retrieve(query_tokens, k=2) # 2-D arrays: (n_queries, k);
# docs holds corpus entries, not positions
print(retriever.method) # 'lucene' — the default variant
print(f"best hit: {docs[0, 0]!r} (score {scores[0, 0]:.2f})")
retriever.save("bm25s_index_corpus") # persist + reload
ret_loaded = bm25s.BM25.load("bm25s_index_corpus", load_corpus=True)lucene
best hit: 'a cat is a feline and likes to purr' (score 0.84)Also worth knowing: Whoosh — the pure-Python engine from the early 2010s — was abandoned (last release 2.7.4, ~2016) but an actively maintained continuation ships as whoosh3 3.54.0 (September 2026, BSD-2-Clause, keeps the whoosh import name) with BM25 ranking, spell-correction and faceting, no server needed. tantivy 0.27.0 (October 2026, MIT) gives Python bindings to Tantivy, the Rust Lucene-alternative that powers Quickwit — a serious embedded option with real analysers. Pyserini 2.4.0 is the research-grade choice: Python bindings to Lucene via Anserini (needs Java 21, Python ≥3.12), with prebuilt indexes for MS MARCO/BEIR/TREC and learned-sparse (SPLADE/uniCOIL) support — it's what IR papers use for reproducible BM25 baselines, not what you'd embed in a product.
4.2 SQLite FTS5: BM25 inside your database#
SQLite ships FTS5, a full-text search virtual table module, compiled into the amalgamation since SQLite 3.9.0 (2015) and present in Python's bundled sqlite3 on essentially every platform. It gives you a real inverted index, BM25 ranking via the bm25() auxiliary function, phrase/prefix/NEAR/boolean queries, and column weights — with zero dependencies. For prototypes, CLI tools, mobile apps, edge deployments and "I just need search in this SQLite file", it's unbeatable.
The catch list up front: BM25 parameters are hard-coded (k1=1.2, b=0.75), the tokenizer set is small (unicode61/ascii/porter/trigram + custom C tokenizers), there's no replication/sharding, and bm25() scores are negative — better matches are more negative (FTS5 multiplies the standard score by −1 so ORDER BY bm25(t) sorts best-first).
Here's the complete demo — real, runnable output:
# fts5_demo.py — BM25 in SQLite, standard library only
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("""
CREATE VIRTUAL TABLE articles USING fts5(
title, body,
tokenize = 'porter unicode61'
)
""")
ARTICLES = [
("Warranty", "Products carry a 12-month warranty covering manufacturing "
"defects. Claims require proof of purchase and the serial "
"number. Damage from misuse or normal wear is excluded."),
("Returns", "Unopened products may be returned within 30 days for a full "
"refund. Opened software licences are non-refundable."),
("Shipping", "Standard delivery takes 3-5 business days. Express delivery "
"costs $12. Remote areas may take longer."),
("Reset your password", "Go to Settings then Security and choose Reset "
"password. The reset link expires after 15 minutes."),
("Error E-4012 at checkout", "Error E-4012 means the payment gateway timed "
"out during checkout. Retry the payment once."),
("Expenses", "Employees may claim travel expenses up to $75 per day. "
"Receipts are required for claims over $25."),
]
cur.executemany("INSERT INTO articles(title, body) VALUES (?, ?)", ARTICLES)
for q in ["warranty", "warranti", '"proof of purchase"', "refund*",
"NEAR(shipping refund, 10)", "title:shipping",
"checkout AND error", "checkout OR warranty", "checkout NOT warranty"]:
rows = cur.execute(
"SELECT rowid, bm25(articles), title FROM articles "
"WHERE articles MATCH ? ORDER BY bm25(articles)", (q,)
).fetchall()
print(f" {q!r}")
for rid, score, title in rows:
print(f" rowid={rid} bm25={score:+.4f} {title!r}")
if not rows:
print(" (no matches)")
print("\n=== column weights: title hit = 10 body hits ===")
for rid, score, title in cur.execute(
"SELECT rowid, bm25(articles, 10.0, 1.0), title FROM articles "
"WHERE articles MATCH 'shipping' ORDER BY bm25(articles, 10.0, 1.0)"
):
print(f" rowid={rid} bm25={score:+.4f} {title!r}")
print("\n=== snippet() and highlight() ===")
for rid, title, snip in cur.execute(
"SELECT rowid, title, snippet(articles, 1, '[', ']', '...', 12) "
"FROM articles WHERE articles MATCH 'refund' ORDER BY bm25(articles)"
):
print(f" [{rid}] {title}: {snip}")
for rid, title, hl in cur.execute(
"SELECT rowid, title, highlight(articles, 0, '**', '**') "
"FROM articles WHERE articles MATCH 'warranty'"
):
print(f" [{rid}] highlighted title: {hl}") 'warranty'
rowid=1 bm25=-1.6264 'Warranty'
'warranti'
rowid=1 bm25=-1.6264 'Warranty'
'"proof of purchase"'
rowid=1 bm25=-1.1365 'Warranty'
'refund*'
rowid=2 bm25=-1.8120 'Returns'
'NEAR(shipping refund, 10)'
(no matches)
'title:shipping'
rowid=3 bm25=-1.3842 'Shipping'
'checkout AND error'
rowid=5 bm25=-3.5730 'Error E-4012 at checkout'
'checkout OR warranty'
rowid=5 bm25=-1.7865 'Error E-4012 at checkout'
rowid=1 bm25=-1.6264 'Warranty'
'checkout NOT warranty'
rowid=5 bm25=-1.7865 'Error E-4012 at checkout'
=== column weights: title hit = 10 body hits ===
rowid=3 bm25=-2.5833 'Shipping'
=== snippet() and highlight() ===
[2] Returns: Unopened products may be returned within 30 days for a full [refund]...
[1] highlighted title: **Warranty**Everything in that output is worth a second look:
'warranti'matched'Warranty'— the porter tokenizer stemmed both sides to the same term. That's stemming working silently and correctly.'"proof of purchase"'is a phrase query — the terms must appear adjacently, in order.'refund*'is a prefix query — any term starting withrefund(any indexed term that begins withrefund; here the Returns article matches through itsrefundterm).NEAR(shipping refund, 10)requires both terms within 10 tokens — correctly found nothing since they're in different docs.title:shippingis a column filter — only thetitlecolumn is searched for that phrase.bm25(articles, 10.0, 1.0)assigns column weights: a "shipping" hit intitlecounts as 10 body hits — our poor-man's BM25F.snippet()returns a relevant fragment with[brackets]around matches;highlight()does the same for a whole column. These are how you build "show why this matched" UI.bm25values are negative; more negative = better.ORDER BY bm25(articles)(ascending) is correct;ORDER BY rankis the documented shortcut (therankcolumn defaults tobm25()).
Operational FTS5 notes that matter in production: the detail=full|column|none option trades index size for phrase/NEAR capability — detail=column drops positions entirely (no phrase or NEAR queries), detail=none drops column info too (no column filters); keep detail=full if you need phrases or trustworthy bm25(); columnsize=0 saves space but breaks bm25() length normalization; INSERT INTO articles(articles) VALUES('optimize') merges segments; secure-delete controls whether deleted text lingers; external-content tables (content='other_table') let FTS5 index text stored elsewhere without duplicating it — the pattern you'd use to index your Module-05 chunk store. fts5vocab is a virtual table that lets you inspect which terms the index learned (SELECT term, doc FROM vocab) — invaluable for debugging "why didn't X match".
4.3 PostgreSQL full-text search and its BM25 extensions#
If your data already lives in Postgres, its built-in full-text search is the zero-new-infrastructure option. Understand precisely what it is: tsvector/tsquery with ts_rank/ts_rank_cd — lexically similar to BM25 but NOT BM25. ts_rank sums lexeme weights with a cover-density variant (ts_rank_cd, from Clarke, Cormack & Tudhope 1999) that rewards proximate matches; there are no k1/b knobs and no IDF saturation curve. For many workloads it's fine; when you need actual BM25 you need an extension.
-- illustrative — Postgres FTS, not BM25
CREATE INDEX articles_fts ON articles
USING GIN (to_tsvector('english', title || ' ' || body));
SELECT title,
ts_rank(to_tsvector('english', title || ' ' || body),
websearch_to_tsquery('english', 'warranty or "proof of purchase"')) AS rank
FROM articles
WHERE to_tsvector('english', title || ' ' || body)
@@ websearch_to_tsquery('english', 'warranty or "proof of purchase"')
ORDER BY rank DESC;Key pieces: to_tsvector('english', text) produces a sorted list of lexemes (stemmed words + positions + weights); tsquery is the query AST; @@ is the match operator; websearch_to_tsquery accepts Google-style syntax (quoted phrases, the lowercase word or, - for NOT — the operator words are lowercase-only) — safer than raw to_tsquery for user input; plainto_tsquery treats everything as plain terms; phraseto_tsquery builds phrase queries; setweight() marks fields (title vs body) for ts_rank's weight vector; GIN indexes store (lexeme → posting list) — literally the same inverted-index structure, with GiST as the alternative for smaller indexes.
When you need real BM25 in Postgres, three extensions exist as of November 2026:
| Extension | What it is | Status / caveats |
|---|---|---|
ParadeDB pg_search |
BM25 full-text search as a native Postgres index type, built on Tantivy (the Rust Lucene) via pgrx; fuzzy search, highlighting, aggregations, |||/&&& operators, pdb.score() |
AGPL-3.0 (Community) or commercial licence (Enterprise); latest v0.26.x in November 2026; PG 15+; requires pgvector since 0.25.0 (the extension's control file declares requires = 'vector'); must be in shared_preload_libraries + restart; index access method gained the primary name paradedb in 0.25.0 (older posts use USING bm25; check the docs for your version) |
pg_textsearch (Timescale/Tiger Data) |
BM25 ranking written in C on Postgres's own storage pages — configurable k1/b, Block-Max WAND top-k, USING bm25(col) index, <@> operator returning negative scores (lower = better, like FTS5) |
PostgreSQL-licensed open source; PG 17–18 only; also needs shared_preload_libraries; younger than ParadeDB (v1.0.0 was its first generally available release; latest v1.5.1, October 2026) |
VectorChord-BM25 (vchord_bm25) |
BM25 ranking via Block-WeakAnd over a bm25vector sparse-vector type + custom tokenizer (pg_tokenizer.rs, Apache-2.0); part of the VectorChord suite alongside vchord (vector search) |
AGPL-3.0, Rust/pgrx, PG 14–18; younger project (v0.3.0, last release Dec 2025) |
All three give you BM25 and keep data in Postgres (no sync pipeline — the 06.8 dream). The trade-off is operational: extensions, licences (AGPL matters if you distribute), and a younger ecosystem than Elasticsearch. Two naming traps when reading old posts: ParadeDB's extension was originally named pg_bm25, renamed pg_search at v0.6.0 (and its index AM gained the primary name paradedb at 0.25.0, replacing the older bm25); pg_textsearch is a separate Timescale/Tiger Data project — check which one a blog post actually means.
4.4 The Lucene family: Elasticsearch, OpenSearch, Pyserini, tantivy, Whoosh#
Elasticsearch (9.5.x as of November 2026; default distribution under the Elastic License) and OpenSearch (3.9.x, Apache-2.0, forked from ES 7.10.2) are the industry-standard search servers. Their full-text path is Lucene: an analysis chain (the mapping field is "analyzer") per field at index time, an inverted index per segment, BM25 similarity by default.
Verified specifics worth knowing:
- BM25 is the default similarity on both. Elasticsearch's
BM25Similaritydefaultsk1=1.2,b=0.75,discount_overlaps=true; per-fieldsimilaritycan be set toboolean(no TF weighting) or custom-tuned. OpenSearch 3.0 changed its default fromLegacyBM25Similarityto Lucene's nativeBM25Similarity— scores dropped by a factor of ~2.2 (ranking unchanged;LegacyBM25remains as a deprecated option). - Lucene switched its default from TF/IDF to BM25 in Lucene 6.0 (2016) — the change you're benefitting from without knowing it.
- The
matchquery analyses the query text with the field'ssearch_analyzer(which defaults to the index"analyzer", but can deliberately differ), then builds a boolean query of term clauses (operator: ORdefault — any term may match;operator: ANDrequires all, implemented viaminimum_should_match).multi_matchrunsmatchacross several fields.match_phraserequires adjacency;fuzziness: "AUTO"enables edit-distance matching;span_neardoes proximity. - Analysers are first-class objects:
standard(Unicode-aware, no stemming),simple(lowercase+tokenize),english(standard + stopwords + Porter stemmer),keyword(whole field as one token), pluspattern,whitespace,icuplugin, language-specific ones (french,german,cjk), and fully custom chains you define in index settings.
Minimal query (illustrative — Elastic Cloud / self-hosted 9.x):
POST /articles/_search
{
"size": 5,
"query": {
"multi_match": {
"query": "warranty cracked screen",
"fields": ["title^3", "body"],
"type": "best_fields",
"operator": "or"
}
}
}(title^3 boosts the title field — field weighting, Part 6. type options: best_fields (default: score = best single field), most_fields (sum across fields — BM25F-ish), cross_fields (treats fields as one — good for AND across fields), phrase, phrase_prefix, bool_prefix.)
When to reach for what: Elasticsearch/OpenSearch when you need the full search-server feature set — faceting, aggregations, fuzzy, highlighting, percolators, a huge ecosystem, managed clouds. They are heavier (JVM, ops burden) but are what "search" means at scale. For BM25-only needs inside Python, bm25s/tantivy are lighter. For research reproducibility, Pyserini.
4.5 Typo-tolerant search engines: Meilisearch, Typesense, Manticore#
A different product category: engines built for instant, typo-tolerant, search-as-you-type experiences — what powers your "did you mean?" box. They all implement lexical retrieval (with their own scoring, often BM25-derived or custom) plus typo tolerance by default.
| Engine | Status (Nov 2026) | Typo tolerance | Notes |
|---|---|---|---|
| Meilisearch | 1.56.x; Community Edition MIT; Enterprise features (incl. sharding — the only EE-exclusive feature) under BUSL-1.1 — check the edition docs for what your version gates | Built-in, on by default: Damerau-Levenshtein via FST; 1–4 chars→0 typos, 5–8→1, 9+→2; first-char typo costs 2 | Single-node CE — no built-in HA; great DX, ranked results, faceting, matchingStrategy |
| Typesense | 30.2 (GPL-3.0 server, Apache-2.0 clients); v31 in development | Built-in | C++ single binary, whole index in RAM, Raft clustering in the OSS server; very fast, sane defaults |
| Manticore Search | 29.x; GPLv3+ (Sphinx fork since 2017) | Built-in fuzzy (option fuzzy=1) |
SQL interface, columnar storage, Galera replication; more database-like |
Typo tolerance in these engines is a ranking signal, not just a filter: phnoe still returns phone docs but ranked below exact matches. Meilisearch's docs describe the mechanism precisely — a Levenshtein automaton intersected with a pre-built FST of the index's terms, computed at query time with no dictionary scan.
When they're the right answer: consumer-facing search boxes, help-centre search, e-commerce — anywhere typo tolerance and instant results matter more than BM25 purity. When they're wrong: you need BM25's exact scoring semantics, complex boolean queries, or tight Postgres/SQL integration — then FTS5/Postgres/extensions/Elasticsearch.
4.6 Learned sparse retrieval: SPLADE and BGE-M3#
The newest member of the lexical family blurs the line between BM25 and embeddings. Learned sparse retrieval keeps the inverted-index infrastructure (term → postings) but replaces hand-crafted term weights with learned ones:
- SPLADE (Formal et al., 2021; SPLADE++, Efficient-SPLADE, uniCOIL variants): a BERT-style encoder outputs a weight for every vocabulary term — including terms not literally in the text (expansion: "car" gets weight on "automobile", "vehicle"). The result is a sparse vector (~100–300 non-zero dims out of ~30k vocab) you can store in any sparse-vector index (Qdrant sparse vectors, Elasticsearch
sparse_vector, pgvectorsparsevec, Lucene via Anserini). Query and document are encoded asymmetrically; scoring is a dot product over the sparse vectors — mathematically BM25-shaped, semantically much richer. - BGE-M3 (
BAAI/bge-m3, BAAI, arXiv 2402.03216): one model producing dense + sparse ("lexical weights") + multi-vector outputs.FlagEmbedding'sBGEM3FlagModel.encode(..., return_sparse=True)returnslexical_weights— per-token weights that behave like learned BM25. "You can obtain token weights (similar to the BM25) without any additional cost when you generate dense embeddings" (model card).
# illustrative — learned sparse weights with BGE-M3 (needs FlagEmbedding + torch)
from FlagEmbedding import BGEM3FlagModel
model = BGEM3FlagModel("BAAI/bge-m3", use_fp16=True)
out = model.encode(
["How do I return a damaged product?"],
return_dense=True, return_sparse=True, return_colbert_vecs=False,
)
# out["lexical_weights"]: {token_id: weight} — learned, expanded, sparse
# convert_id_to_token maps each {token_id: weight} dict to {token_string: weight}
print(model.convert_id_to_token(out["lexical_weights"])[0])Why this matters to this lesson: learned sparse vectors are the lexical side of hybrid search done properly — they fix BM25's vocabulary-mismatch problem (the thing synonyms/expansion in 5.2 hacks at) while keeping inverted-index speed and interpretability. The dense+sparse fusion is exactly what 06.8 covers; Qdrant/Elasticsearch/pgvector all store these as first-class sparse vectors (06.5 has the per-store details). Also note doc2query-style query/document expansion — generating likely query terms and appending them to the document — is the classical precursor of learned expansion.
Part 5: Query handling#
5.1 Query languages: phrases, boolean, prefix, proximity, columns#
"Keyword search" is not one thing — it's a spectrum from LIKE '%foo%' to full Boolean query languages. The features that matter:
| Feature | Syntax examples | What it does | Where |
|---|---|---|---|
| Terms | warranty refund |
Match docs containing the terms (AND or OR per engine default) | everywhere |
| Phrases | "proof of purchase" |
Terms must appear adjacently, in order | FTS5, ES match_phrase, Lucene PhraseQuery |
| Prefix | warran*, E-40* |
Any indexed term with the prefix | FTS5 *, ES wildcard/prefix, needs prefix index at scale |
| Boolean | AND, OR, NOT, &&, ` |
, !` |
|
| Proximity / NEAR | NEAR(shipping refund, 10) |
Terms within N tokens of each other | FTS5 NEAR, Lucene SpanNearQuery, ES span_near |
| Column/field filter | title:shipping, {title body}:refund |
Restrict clause to fields | FTS5 column filters, ES title:warranty |
| Fuzzy | warrenty~, fuzziness: AUTO |
Match within edit distance | ES/Lucene FuzzyQuery, Meilisearch/Typesense built-in |
| Wildcard | w*nty, *refund* |
Pattern match on terms (leading * is expensive) |
ES wildcard, Lucene WildcardQuery |
The engine differences that bite people:
- Implicit operator: FTS5 treats space-separated terms as implicit AND (
warranty refund= both required). Lucenematchdefaults to OR (minimum_should_matchconfigurable). PostgreSQLwebsearch_to_tsquerytreats space-separated words as AND,orkeyword as OR. Know your engine's default before debugging "missing results". - Stopwords in phrases:
"to be or not to be"under a stopword-removing analyser becomes a 2-term phrase query — positions still work because stopword positions are preserved in most engines (Lucene keeps positions for removed stopwords; FTS5 has no stopword removal at all, so positions are always intact). - Case: FTS5 unicode61 is case-insensitive; Lucene analysers lowercase; a
keywordfield is case-sensitive. Mixed case sensitivity across fields is a classic "works in title, fails in body" bug.
To make this concrete, here's a ~70-line mini query language evaluated over the inverted index from 2.1 — supporting terms, "phrases", prefix*, AND/OR/NOT, and parentheses. It's the same shape as every real FTS query parser:
# mini_querylang.py — a tiny FTS query parser + evaluator (stdlib only)
import re
from collections import defaultdict
TOKEN_RE = re.compile(r"[a-z0-9]+")
def tokenize(text): return TOKEN_RE.findall(text.lower())
# index over the Acme corpus (title + body tokenized together)
CORPUS = [
("handbook-warranty", "Warranty", "Products carry a 12-month warranty covering manufacturing defects. Claims require proof of purchase."),
("handbook-returns", "Returns", "Unopened products may be returned within 30 days for a full refund."),
("handbook-shipping", "Shipping", "Standard delivery takes 3-5 business days. Express delivery costs $12."),
("help-reset-password", "Reset your password", "Go to Settings then Security and choose Reset password. The reset link expires after 15 minutes."),
("help-error-e4012", "Error E-4012 at checkout", "Error E-4012 means the payment gateway timed out during checkout. Retry the payment once."),
("ticket-1042", "Checkout fails for card payments", "Customer reports checkout fails with error E-4012. Transaction ID TXN-8841."),
("contract-liability", "Liability", "The supplier's total liability shall not exceed the fees paid in the preceding 12 months."),
]
DOCS = [tokenize(t + " " + b) for _, t, b in CORPUS]
IDS = [d for d, _, _ in CORPUS]
N = len(DOCS)
postings = defaultdict(lambda: defaultdict(list))
for i, toks in enumerate(DOCS):
for pos, t in enumerate(toks):
postings[t][i].append(pos)
def term_docs(term):
if term.endswith("*"):
p = term[:-1]
return {d for t, locs in postings.items() if t.startswith(p) for d in locs}
return set(postings.get(term, {}))
def phrase_docs(phrase):
toks = tokenize(phrase)
if not toks: return set()
out = set()
for d in set(postings.get(toks[0], {})):
for start in postings[toks[0]][d]:
if all(start + k in postings.get(t, {}).get(d, [])
for k, t in enumerate(toks)):
out.add(d); break
return out
def ev(node):
k = node[0]
if k == "term": return term_docs(node[1])
if k == "phrase": return phrase_docs(node[1])
if k == "and": return ev(node[1]) & ev(node[2])
if k == "or": return ev(node[1]) | ev(node[2])
if k == "not": return set(range(N)) - ev(node[1])
raise ValueError(k)
def parse(query):
toks = re.findall(r'"[^"]+"|\(|\)|\bAND\b|\bOR\b|\bNOT\b|[^\s()]+', query)
pos = 0
def peek(): return toks[pos] if pos < len(toks) else None
def eat():
nonlocal pos; t = toks[pos]; pos += 1; return t
def p_or():
l = p_and()
while peek() == "OR": eat(); l = ("or", l, p_and())
return l
def p_and():
l = p_not()
while True:
t = peek()
if t == "AND" or (t is not None and t not in ("OR", ")")):
if t == "AND": eat()
l = ("and", l, p_not())
else: break
return l
def p_not():
if peek() == "NOT": eat(); return ("not", p_not())
return p_atom()
def p_atom():
t = eat()
if t == "(":
n = p_or(); assert eat() == ")"; return n
return ("phrase", t.strip('"')) if t.startswith('"') else ("term", t.lower())
tree = p_or(); assert pos == len(toks); return tree
for q in ['warranty', 'checkout error', '"proof of purchase"', 'e*',
'checkout NOT warranty', '(warranty OR returns) AND refund',
'damaged refund']:
try:
hits = sorted(ev(parse(q)))
print(f" {q!r:38} -> {[IDS[i] for i in hits]}")
except Exception as e:
print(f" {q!r:38} -> ERROR {e}") 'warranty' -> ['handbook-warranty']
'checkout error' -> ['help-error-e4012', 'ticket-1042']
'"proof of purchase"' -> ['handbook-warranty']
'e*' -> ['handbook-shipping', 'help-reset-password', 'help-error-e4012', 'ticket-1042', 'contract-liability']
'checkout NOT warranty' -> ['help-error-e4012', 'ticket-1042']
'(warranty OR returns) AND refund' -> ['handbook-returns']
'damaged refund' -> []Two instructive results: 'e*' matched 5 of 7 docs — prefix e hits every indexed term starting with e (error, express, expires, exceed, and even the single-letter e our tokenizer split out of E-4012), while handbook-warranty and handbook-returns contain no e-initial term at all. Prefix queries only help when a term actually starts with the prefix — and short prefixes like e* are nearly useless. And 'damaged refund' returned [] under implicit AND — no document contains both terms — while BM25 scoring (OR-style sum) would still rank docs containing either. Boolean filtering and ranked scoring answer different questions; engines compose them.
5.2 From natural language to keyword queries#
Users don't type title:warranty AND (refund OR return). They type "how do I get my money back for a broken screen?" Your job: turn that into good keyword queries. The techniques, cheapest first:
- Stopword stripping — drop "how", "do", "I", "my", "for", "a" (your engine's stopword list or a small regex list).
- Keyword extraction — keep content words; optionally use term frequency/IDF of the query itself or a tiny model to rank which words matter.
- Synonym and acronym expansion — the highest-value, lowest-cost trick. Maintain a per-domain table:
# expand.py — synonym/acronym expansion over query terms (stdlib only)
import math, re
from collections import defaultdict
SYNONYMS = {
"broken": ["damaged"],
"shattered": ["damaged", "broken"],
"money back": ["refund", "reimbursement"],
"warranty": ["guarantee"],
"screen": ["display"],
"e-4012": ["payment timeout"], # error code -> its documented meaning
"sla": ["service level agreement"], # acronym -> expansion
}
def expand(query: str) -> list[str]:
"""Return query tokens plus tokens of any matching synonyms."""
out = re.findall(r"[a-z0-9]+", query.lower())
# match keys as token *sequences*, so punctuation can't break multi-word
# keys ('money back?' still hits 'money back'; 'E-4012' -> ['e','4012'])
for key, syns in SYNONYMS.items():
kt = re.findall(r"[a-z0-9]+", key)
if any(out[i:i + len(kt)] == kt
for i in range(len(out) - len(kt) + 1)):
for syn in syns:
out.extend(re.findall(r"[a-z0-9]+", syn))
return list(dict.fromkeys(out)) # dedupe: repeats inflate BM25 tf
print(expand("my screen is broken, can I get money back?"))
print(expand("what is the SLA for E-4012?"))['my', 'screen', 'is', 'broken', 'can', 'i', 'get', 'money', 'back',
'damaged', 'refund', 'reimbursement', 'display']
['what', 'is', 'the', 'sla', 'for', 'e', '4012',
'payment', 'timeout', 'service', 'level', 'agreement']Then feed the expanded terms to BM25 as an OR-set — matching any variant adds its (usually small) IDF. On the 5-doc corpus, query broken alone finds nothing (no doc contains "broken"); expanded to broken + damaged it retrieves doc2 (0.57), doc1 (0.53), doc4 (0.53) — real output from the prototype. That's vocabulary-mismatch fixed for free.
-
LLM query rewriting — the 2026 version: ask a small fast model to rewrite the question into keyword queries, extract filters, or produce synonyms. Preview: 06.10 covers multi-query/HyDE evaluation; Module 07 owns the RAG-side query understanding. The pattern to steal now: structured output (03.4) returning
{ "keywords": [...], "must_terms": [...], "synonyms": {...} }, then run each variant through your lexical retriever and fuse — RRF fusion is 06.8's job. -
Spelling correction before search — "warrenty" → "warranty". Cheap version: edit-distance-1 candidate generation against your top-N terms by DF (a bounded dictionary scan, not the whole vocab); engine version: Meilisearch/Typesense do it natively. See 5.3.
5.3 Typos, fuzzy matching and edit distance#
"warrenty", "warrenty", "waranty" — users misspell constantly, and exact-match lexical search returns nothing. Edit distance (Levenshtein: insertions, deletions, substitutions; Damerau adds transpositions — "teh"→"the" as one edit) is the measure. Three ways engines exploit it:
- Query-time fuzzy terms: Lucene
FuzzyQuery/Elasticsearchfuzzinessbuilds a Levenshtein automaton over the term dictionary — finds indexed terms within distance d of the query term, then scores them.AUTOfuzziness = distance 0 for terms ≤3 chars, 1 for 4–5, 2 for longer (approximate — check your version's docs). - Index-time n-grams: trigram indexes make typo matching a set-intersection problem — robust but fuzzy scores.
- Engine-native typo tolerance: Meilisearch/Typesense described in 4.5.
The trap: fuzzy on short terms and identifiers is dangerous. E-4012 with fuzziness can match E-4011, E-4021, E-5012 — for identifiers you usually want exact match, not fuzzy. Apply fuzzy to prose fields, exact to ID fields — another argument for per-field policy.
5.4 Keeping user input out of trouble#
Two different injection risks, often conflated:
SQL injection — solved the normal way: WHERE articles MATCH ? with parameters, never f-string the query into SQL. psycopg/sqlite3/SQLAlchemy all parameterize.
FTS syntax injection — sneakier. MATCH takes a query language, not plain text. If you interpolate user input: MATCH 'warranty" OR title:secret' or unbalanced quotes/parens — you get parse errors (sqlite3.OperationalError: unterminated string, verified) or, worse, queries the user never intended (OR clauses dumping the whole corpus, NOT clauses hiding everything). Real output from our FTS5 demo:
# parameterized: safe from SQL injection, but hostile FTS syntax still parses
user_input = 'refund" OR 1=1 --'
cur.execute("SELECT count(*) FROM articles WHERE articles MATCH ?", (user_input,))
# -> sqlite3.OperationalError: unterminated string (error, not injection)
# treat user input as ONE phrase — quotes stripped first, then re-quoted
safe = '"' + user_input.replace('"', '""') + '"'
cur.execute("SELECT count(*) FROM articles WHERE articles MATCH ?", (safe,))
# -> 0 rows: literal phrase match, no syntax effectsProduction rules: (1) parameterize always; (2) for free-text "search this" boxes, wrap the sanitized input as a phrase or split into terms yourself and AND/OR them explicitly; (3) for power-user query bars, document the syntax and validate/escape per engine (Elasticsearch's query_string query has an "analyze_wildcard" flag and escape support; Lucene has QueryParser.escape()); (4) rate-limit and timeout expensive wildcard/fuzzy queries — *a* leading-wildcard scans are a classic DoS.
Part 6: Field weighting and structure#
Deep-dive
6.1 Why fields matter#
A hit in the title is worth more than the same hit buried in a 4,000-word body. A hit in a heading means the section is about the topic; a hit in metadata (product name, SKU) is nearly definitive. BM25 scores a flat document; real systems score structured documents — and there are three mechanisms:
- Index-time field weights (BM25F proper) — Robertson, Zaragoza & Taylor's 2004 extension: compute a length-normalized term frequency per field, combine across fields with per-field weights
w_c, then apply saturation once. Title hits getw_title=5–10, bodyw_body=1. - Query-time boosts —
title^3in Elasticsearchmulti_match, per-fieldbm25(articles, 10.0, 1.0)column weights in FTS5 (verified above: a title hit counted as 10 body hits). Cheaper to change, but weights apply at query time. - Separate fields/collections — index title and body as distinct fields (or distinct collections) and merge scores — the score-comparability problem returns (06.6 covers multi-index merging).
BM25F-lite, runnable — same corpus, title matches weighted 2×:
# bm25f_toy.py — field-weighted BM25 (stdlib only)
import math, re
from collections import defaultdict
TOKEN_RE = re.compile(r"[a-z0-9]+")
def tokenize(t): return TOKEN_RE.findall(t.lower())
CORPUS = [
("Warranty", "Products carry a 12-month warranty covering manufacturing defects. Damage from misuse is excluded."),
("Returns", "Unopened products may be returned within 30 days for a full refund. Opened licences are non-refundable. Return shipping is free for manufacturing defects."),
("Shipping", "Standard delivery takes 3-5 business days. Express delivery costs $12. Remote areas may take longer."),
("Expenses", "Employees may claim travel expenses up to $75 per day without approval. Receipts are required for claims over $25."),
("Error E-4012", "Error E-4012 means the payment gateway timed out during checkout. Retry the payment once."),
]
FIELDS = ["title", "body"]
W = {"title": 2.0, "body": 1.0} # field weights
K1, B = 1.2, 0.75
postings = defaultdict(lambda: defaultdict(list)) # term -> (field,doc) -> positions
flen = {f: [] for f in FIELDS}
for i, (title, body) in enumerate(CORPUS):
for f, text in zip(FIELDS, (title, body)):
toks = tokenize(text)
flen[f].append(len(toks))
for pos, t in enumerate(toks):
postings[t][(f, i)].append(pos)
N = len(CORPUS)
df = {t: len({d for (_, d) in locs}) for t, locs in postings.items()}
avg = {f: sum(flen[f]) / N for f in FIELDS}
def score(query_terms, doc_id):
total = 0.0
for term in query_terms:
pseudo_tf = 0.0
for (field, d), poss in postings.get(term, {}).items():
if d == doc_id:
norm = 1 - B + B * flen[field][d] / avg[field]
pseudo_tf += W[field] * len(poss) / norm
if pseudo_tf == 0: continue
n = df[term]
idf = math.log(1 + (N - n + 0.5) / (n + 0.5))
total += idf * (pseudo_tf * (K1 + 1)) / (pseudo_tf + K1)
return total
for s, i in sorted(
((score(["shipping"], i), i) for i in range(N)), key=lambda x: -x[0]
)[:3]:
print(f" {CORPUS[i][0]:12s} {s:.4f}") Shipping 1.3090
Returns 0.7621
Warranty 0.0000Read it as a controlled experiment: shipping occurs once in each of the two docs, but in "Shipping" it sits in the title (weight 2.0) and in "Returns" only in the body (weight 1.0) — same term frequency, different field, ~1.7× the score. "Warranty" scores 0 because shipping appears nowhere in it — BM25F still scores zero for absent terms.
How the engines do it in practice:
| Engine | Mechanism | Syntax |
|---|---|---|
| SQLite FTS5 | per-column weights in bm25() |
bm25(t, 10.0, 1.0) (verified) |
| Elasticsearch/OpenSearch | query-time field^N boosts and "boost" on match/bool clauses; per-field similarity settings (incl. boolean) — index-time field boosts were removed in ES 8.x |
"fields": ["title^3","body"] |
| Lucene | BM25FSimilarity for true BM25F; BooleanQuery with per-clause boosts otherwise |
Java API |
PostgreSQL ts_rank |
optional weights float4[] first arg + setweight() A–D labels on tsvector fields |
ts_rank('{0.1,0.2,0.4,1.0}'::float4[], vec, query) |
| Qdrant | per-field named vectors or payload-indexed text; fusion is query-side (06.8) | named vectors API |
Practical guidance: start with query-time boosts (cheapest to iterate); move to BM25F/index-time weights when boosts stop being enough; keep per-language fields separate when mixing languages (a Chinese body shouldn't share statistics with English titles — IDF is per-index).
Part 7: Scale and operations#
Reference
7.1 Index size and memory#
Rule of thumb arithmetic (estimates — verify per engine): a posting entry costs ~4–12 bytes depending on doc-ID compression and whether positions are stored. For N docs × L avg tokens × ~8 bytes:
- 100k chunks × 300 tokens ≈ 30M postings ≈ ~250 MB raw, less with compression (Lucene uses delta+variable-byte encoding; FTS5 uses varints — typically 2–5× smaller).
- Positions roughly double-to-triple index size — needed only for phrase/NEAR/proximity. FTS5's
detail=columnoption drops positions (keeps column of each match);detail=nonedrops more (no bm25). - Term dictionary: unique terms × (term bytes + offsets). English typically yields on the order of a million unique terms per billion tokens — a rough order of magnitude, heavily corpus-dependent.
Compare with the dense side (06.4): 1M chunks × 1536 dims × 4 B = 6.1 GB of vectors alone — keyword indexes are typically smaller than the vector indexes for the same corpus, and always cheaper to build (no model calls, CPU-only).
7.2 Updates, deletes, segments and merges#
Keyword indexes are append-optimized: new documents go into new segments (immutable sorted runs); queries search all segments and merge results. Deletes are tombstones — the doc is marked deleted but its postings remain until merge/expunge. This is why:
- Inserts are fast (append to the active segment) but deletes leave garbage until merge — FTS5's
'optimize'/'merge'commands, Lucene'sforceMerge, Elasticsearch's_forcemerge. - Segment count affects query latency (more segments = more posting lists to intersect) — engines auto-merge with tiered policies.
- A deleted-then-readded document can transiently appear twice (tombstone + new segment) — engines dedupe by doc ID, but watch for it in custom implementations.
- Read-after-write: most engines make new docs searchable within the refresh interval (ES default 1s); FTS5 is immediate (same transaction); PostgreSQL FTS is transactional.
7.3 Refresh latency and near-real-time search#
"How quickly does new content become searchable?" ranges from transactional (FTS5, Postgres — the index update commits with the row) to near-real-time (Elasticsearch ~1s refresh, Meilisearch ~instant task queue, Typesense immediate) to batch (nightly rebuilds, warehouse search). For RAG freshness (Module 07) this is a product decision: a help-centre answer must reflect today's policy; a research corpus can lag a day.
7.4 Sharding, caching, replication#
At scale, engines shard the term dictionary + postings across nodes (Elasticsearch shards, Typesense Raft groups, SolrCloud-style). Term-dictionary lookup is the hot path — engines cache it aggressively; query-result caching helps repeated queries but watch privacy (cached results can leak across tenants — same ACL-filtering rules as vectors, 06.6). Replication is standard primary+replica; the lexical index is usually smaller than the vector index so it's cheaper to replicate — one reason hybrid systems often keep BM25 in the lighter store.
7.5 Analyser changes, reindexing and IDF drift#
Two maintenance facts people learn the hard way:
- Changing the analyser = full reindex. The postings were built under the old tokenization; there's no incremental path. Plan it like an embedding-model change (06.1, 05.9): blue/green index, verify, cut over.
- IDF drifts as the corpus grows.
dfandavgdlare corpus statistics baked into scores at query time (computed live in most engines — good) but document-length norms are often precomputed at index time (Lucene stores norms per doc). Adding a million docs changes IDF for every term — scores shift even with identical queries. This is normal and fine (ranking is relative), but it means a score threshold tuned last quarter is stale this quarter — re-evaluate thresholds on a schedule, and remember BM25 scores aren't portable across corpus versions anyway.
7.6 Multilingual indexes#
Options: (a) one index, per-document language detection routing to per-field analysers; (b) separate indexes/collections per language (06.6 covers routing by language); (c) language-agnostic analysers (ICU) that handle many scripts acceptably. IDF is computed per index — mixing languages in one index lets a common word in language A deflate IDF for the same string in language B (rare but real for shared scripts like kanji). For CJK specifically, see 2.7.
7.7 Cost arithmetic#
Keyword search's superpower is that it's nearly free compared to everything else in the retrieval stack: no embedding API calls at query time (the query analyser is microseconds), no GPU, index build is CPU-bound and fast (Lucene indexes ~100MB text/sec/core order of magnitude — verify on your hardware). The costs are operational: index storage, merge I/O, and the second system to keep in sync with your vector store (06.8 covers the dual-write problem). If your corpus is <100k chunks and queries are simple, SQLite FTS5 or bm25s may be your entire keyword stack — don't deploy Elasticsearch for 20k documents.
Part 8: Evaluating BM25 on your data#
BM25 is the baseline every retrieval experiment needs. Before you add embeddings, hybrid fusion or rerankers, measure plain BM25 on your labelled query set (06.10 owns the harness and metrics): if BM25 already hits 0.9 recall@10 on your questions, your corpus is lexically-friendly and hybrid may add little; if it hits 0.4, you know exactly how much semantic retrieval must contribute.
Three warnings specific to lexical eval:
- Lexical leakage in synthetic questions: if your eval questions were generated by an LLM that paraphrased document text, they may share rare terms with the source chunk — BM25 looks artificially good. 10A.2 covers the leakage problem; write some questions without looking at the documents (paraphrase-first, keywords-second).
- Analyser sensitivity: run the eval under your production analyser, not
doc.split(). Stemming/stopword choices swing recall by real margins. - Score thresholds don't transfer: a BM25 cutoff tuned on one corpus version won't hold after reindexing — evaluate rankings (recall@k, MRR, nDCG), not absolute scores.
Failure gallery#
| Failure | Symptom | Cause | Fix |
|---|---|---|---|
| Analyser mismatch | Query returns 0 results, no error | Index stemmed, query path not (or different tokenizer) | One analyser for index+query; version it (2.8) |
| Stopword removal breaks phrases | "to be or not to be" fails |
Stopwords removed before phrase matching | Keep positions; domain-aware stop lists; keyword field for exact text |
| Stemming collision | university matches universe |
Over-stemming Porter rules | Accept for recall; keep unstemmed field; evaluate |
| Un-analysed identifiers | E-4012 never matches |
Tokenizer splits on -/_, or field is text not keyword |
Custom tokenizer/char filter; keyword field for IDs |
| Long-document bias | 4,000-word contract outranks 50-word FAQ | b too low or tf saturation too weak | Raise b toward 1; check avgdl sanity; field weights |
| Term stuffing wins | SEO-spam doc tops results | k1 too high / no length norm | Lower k1, raise b; dedupe boilerplate at ingest |
| Negative/zero IDF confusion | Common terms score oddly | df > N/2 under Robertson IDF | Use +1 variant (Lucene/ES) or rank_bm25's epsilon floor; don't hand-roll Robertson-naive IDF |
| FTS syntax crash | OperationalError: unterminated string |
User input interpolated into MATCH | Parameterize + quote-as-phrase (5.4) |
| Wildcard DoS | Query latency spikes | Leading * / fuzziness on huge vocab |
Restrict wildcard fields; cap fuzziness; timeouts |
| Stale thresholds | "Worked last month, broken now" | IDF drift after corpus growth | Re-evaluate on schedule; rank-based metrics only |
| CJK returns nothing | Chinese queries never match | Whitespace tokenizer on unsegmented text | Language segmenter or char n-grams (2.7) |
| Deleted docs still found | Ghost results after delete | Tombstones not yet merged | Optimize/forceMerge; check engine's delete visibility |
Decision table: which keyword tool?#
| Situation | Use | Why |
|---|---|---|
| Learning / teaching / tiny corpus (<10k docs) | Your own BM25 (this lesson) or bm25s/rank_bm25 |
Zero deps, full control, you understand every number |
| Prototype or CLI tool on SQLite | SQLite FTS5 | BM25 built in, transactions, no server, ships with Python |
| Data already in Postgres, simple needs | Postgres FTS (tsvector/ts_rank) |
Zero new infra; accept it's not BM25 |
| Postgres + real BM25 needed | ParadeDB pg_search or VectorChord-BM25 |
BM25 in-place; AGPL/licence + maturity caveats |
| Serious search product, facets, fuzzy, scale | Elasticsearch or OpenSearch | The industry standard; ops cost is real |
| Research / IR papers / reproducible baselines | Pyserini | Prebuilt indexes, Lucene correctness, SPLADE support |
| Embedded Rust-grade search in Python | tantivy |
Real Lucene-family engine, no JVM |
| Pure-Python engine, no server, spell-check | whoosh3 |
Maintenance caveat: community fork |
| Consumer search box, typo tolerance, instant | Meilisearch / Typesense | Built for UX, not BM25 purity; check HA/licensing |
| Semantic+lexical learned weights | SPLADE / BGE-M3 sparse → hybrid | 06.8 |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "BM25 is obsolete now that embeddings exist." | It's the strongest cheap baseline and the lexical half of every hybrid system. Embeddings miss exact terms; BM25 misses paraphrases. You need both (06.8). |
| "BM25 scores are probabilities." | They're unbounded scores meaningful only for ranking within one index at one corpus state. Never threshold them across versions. |
| "k1=1.2, b=0.75 are magic constants." | They're robust defaults from the IR literature. Tune on your labelled set (06.10); differences are usually small. |
| "ts_rank in Postgres is BM25." | It's a different ranking function (lexeme weights + cover density). Close cousin, not the same algorithm. |
| "Stopwords should always be removed." | They save index space and rarely affect ranking (IDF handles them), but they break phrase queries and can delete meaningful words ("not", "no"). Domain decision. |
| "Stemming always helps." | It boosts recall but causes collisions (university/universe) and can hurt precision-sensitive fields. Evaluate per corpus; keep unstemmed fields for exact match. |
| "You can change the analyser without reindexing." | Postings are built from analysed terms — analyser changes require full reindex, like an embedding model change. |
| "Fuzzy matching is always safe." | On identifiers (E-4012→E-4021) fuzzy is dangerous. Exact for IDs, fuzzy for prose — per-field policy. |
| "BM25 needs a search engine." | SQLite FTS5 does BM25 in your existing database; bm25s does it in 50 lines of NumPy. Engines earn their cost at scale/features, not at the algorithm. |
| "Synonym expansion is free recall." | It trades precision for recall and can produce embarrassing matches (java→coffee). Curate per-domain, version it, evaluate it. |
Key takeaways#
- Keyword search is not legacy — it's the exact-match complement to dense retrieval, and BM25 is its best-known ranking function. Dense misses IDs/codes/rare terms; BM25 misses paraphrase. Hybrid is 06.8.
- The inverted index (term → postings with tf/positions) is the shared substrate of every keyword engine; ~30 lines of Python builds a working one.
- Analysis is the product: case folding, Unicode normalization, stopwords, stemming, n-grams, identifier handling and CJK segmentation decide what is findable. Analyser mismatch between index and query is the #1 silent failure; analyser changes require reindex.
- BM25 = saturated term frequency × IDF × length normalization, with
k1(saturation) andb(length penalty) as the only knobs. Defaults 1.2/0.75 nearly everywhere; FTS5 hard-codes them; rank_bm25 ships k1=1.5. - Variants matter less than you think: BM25F (fields), BM25L/+ (long docs) — know they exist, default to Okapi, reach for variants on evidence.
- Tooling ladder: own code/bm25s/rank_bm25 → SQLite FTS5 → Postgres FTS (+pg_search/vchord_bm25 for real BM25) → Elasticsearch/OpenSearch → Meilisearch/Typesense for UX-first search → Pyserini/tantivy/Whoosh3 for niches.
- Query handling is half the product: phrases, boolean, prefix, NEAR, column filters, NL→keyword rewriting, synonyms, typos — and never let raw user input reach the query parser unescaped.
- BM25 is your baseline: measure it before adding anything fancy; its scores are for ranking, not thresholds; IDF drifts as the corpus grows.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Inverted index | Term → postings (doc IDs, term frequencies, positions) mapping that makes keyword lookup fast |
| Posting / postings list | The per-term list of documents containing it, with positions |
| Document frequency (df) | Number of documents containing a term |
| Term frequency (tf) | How often a term occurs in one document |
| IDF | Inverse document frequency — a term's rarity weight |
| TF-IDF | The predecessor family: tf × idf without BM25's saturation/length norm |
| BM25 / Okapi BM25 | The ranking function: Σ idf × tf·(k1+1)/(tf + k1·lengthNorm) |
| k1 / b | BM25's saturation and length-normalization parameters (defaults ~1.2 / 0.75) |
| BM25F | BM25 extended to multiple weighted fields with per-field length normalization |
| BM25L / BM25+ | Variants fixing over-penalization of very long documents (Lv & Zhai) |
| Analyser (analysis chain) | The index-time pipeline (char filters → tokenizer → token filters) that canonicalizes text for search |
| Tokenizer (search) | The analysis component splitting text into indexable terms — distinct from an LLM's subword tokenizer |
| Stopword | A high-frequency low-value word often removed at analysis time |
| Stemming / lemmatization | Crude suffix-stripping to a root / dictionary-based base-form reduction |
| N-gram / edge n-gram / trigram | Fixed-length character sequences indexed for substring/fuzzy matching |
| Prefix index | Extra index making term* prefix queries fast |
| Phrase query / NEAR query | Adjacent-terms / within-N-tokens query operators |
| Column/field filter | Restricting a query clause to specific fields (FTS5 title:x, ES title:x) |
| Fuzzy matching / edit distance | Matching terms within N insertions/deletions/substitutions (Levenshtein/Damerau) |
| tsvector / tsquery / ts_rank | PostgreSQL's lexeme vector, query AST, and ranking functions (not BM25) |
| GIN index | Postgres's generalized inverted index for tsvector columns |
| Segment / merge / tombstone | Immutable index runs, their background consolidation, and delete markers |
| Learned sparse retrieval / SPLADE / lexical weights | Neural sparse vectors over the vocabulary with learned term weights and expansion (BGE-M3, SPLADE) |
| Hybrid search | Combining lexical and dense retrieval — 06.8 |
Exercises#
- Inverted index (2.1): extend
inv_index.pyto store positions and implementphrase_docs("proof of purchase"). Verify it returns only docs containing the exact phrase. - BM25 by hand (3.5): recompute doc2's score for
damaged refundstep by step on paper (idf, norm, tf part), then check your number against the script output. Compare it with the TF-IDF score from 3.4 — why does only BM25 separate docs 1 and 2? - k1 sensitivity (3.6): build a corpus with one 2,000-token document and one 50-token document both containing "refund" once. Sweep
k1 ∈ {0.5, 1.2, 2.0}×b ∈ {0, 0.75, 1.0}and find where the ranking flips. Explain which parameter did the work. - Analyser experiment (2.4–2.8): tokenize
"The warranties for E-4012 and SKU-88 cover café-level damage"three ways — your[a-z0-9]+regex, FTS5porter unicode61, and FTS5trigram. Compare the term lists and predict which queries each supports. - FTS5 in anger (4.2): load 20 real help articles into
articles, then write five queries a user would actually type. Which return nothing? Fix them with synonyms, prefix or column filters. - Query language (5.1): add
NEAR(a b, N)support tomini_querylang.pyusing the positions already stored. TestNEAR(error refund, 5)vsNEAR(error refund, 50). - Security (5.4): write a
sanitize_fts_query(user_input)function that converts free text into a safe FTS5 MATCH string (terms ANDed, special chars handled). Test it against'refund" OR 1=1 --','"unclosed, andNEAR(. - BM25 baseline (Part 8): take the Module-05 chunk corpus (or the Acme slice), write 10 questions with known relevant chunks, and compute recall@5 for plain BM25 via bm25s or your own implementation. This is your baseline for 06.10.
Hints and what you should see
(All numbers below come from running this lesson's own stdlib code, with SQLite 3.53.4 for the FTS5 parts. FTS5 needs no install.)
-
Import
postingsandtokenizefrominv_index.pyand check each start position of the first term, then look for the following terms atstart + k:python def phrase_docs(phrase): toks = tokenize(phrase) if not toks: return [] return sorted(d for d in postings.get(toks[0], {}) if any(all(s + k in postings.get(t, {}).get(d, []) for k, t in enumerate(toks)) for s in postings[toks[0]][d]))You should see
phrase_docs("proof purchase") == [0]andphrase_docs("damaged refund") == [0](doc 0 has them adjacent; docs 1 and 3 contain both words but not next to each other), whilephrase_docs("refund damaged") == [](order matters) andphrase_docs("damaged")returns[0, 1, 3](a one-word phrase is a plain term lookup). Note thatphrase_docs("proof of purchase")returns[]on these five documents, because their text was written without the word "of" ("... proof purchase receipt"). That is not a bug in your code. On the Acme text in 5.1 the same phrase does hithandbook-warranty. -
Doc2 has 5 tokens and
avgdlis 5.8, sonorm = 1 - 0.75 + 0.75 × 5/5.8 = 0.896552. For one occurrence of a term the tf part is2.2 / (1 + 1.2 × 0.896552) = 1.059801; multiplied byidf = 0.538997that is0.571229per term,1.142458for the two terms. Doc1 has 6 tokens,norm = 1.025862, tf part0.986090, so0.531499per term and1.062998in total. Both match the script output of 3.5. TF-IDF gives docs 1, 2 and 4 the same1.078because it never looks at length, so only BM25 can put doc2 (the shortest) ahead. -
Use one corpus with the two documents plus a few short filler documents (so that
idfandavgdlare fixed), and comparebm.term_score("refund", 0)withbm.term_score("refund", 1). With 10 documents (a 2,000-token one, a 50-token one and eight 3-token fillers),idf("refund")is the same for both, and you should see:k1b=0(long / short)b=0.75(long / short)b=1.0(long / short)0.5 1.482 / 1.482 0.469 / 1.829 0.382 / 1.983 1.2 1.482 / 1.482 0.327 / 2.149 0.259 / 2.528 2.0 1.482 / 1.482 0.278 / 2.388 0.219 / 2.999 At
b=0the two documents tie at everyk1(no length penalty at all); the momentb > 0the short document wins, so the ranking "flips" from a tie to short-first at any positiveb.k1never changes the order, it only changes how big the gap is (short/long ratio atb=0.75: 3.9x atk1=0.5, 6.6x at 1.2, 8.6x at 2.0). Sobdid the work. Your absolute scores differ if your filler documents differ (they changeavgdl), but the tie atb=0and the growth of the ratio withk1andbdo not. -
The three term lists for
"The warranties for E-4012 and SKU-88 cover café-level damage":Analyser Terms Consequence [a-z0-9]+regexthe warranties for e 4012 and sku 88 cover caf level damageéis not ina-z, socafébecomescaf;E-4012becomese+4012; no stemming, sowarrantydoes not matchwarrantiesFTS5 porter unicode614012 88 and cafe cover damag e for level sku the warrantistems ( warranti,damag), folds the accent (cafematchescafé), still splitsE-4012andSKU-88FTS5 trigram58 overlapping 3-character grams ( caf,afé,fé-,-le,e-4,-40,401...)substring and identifier-friendly, no stemming, no accent folding Queries to try with
MATCH:warrantyandwarrantiesboth match under porter and onlywarrantiesunder trigram (warrantyhas the gramntythat the text lacks);cafematches under porter but not trigram (which does matchcaféand the fragmentamage);4012andskumatch in both;sku88matches in neither. Also notice that an unquotede-4012in aMATCHstring raisesno such column: 4012(the-is read as syntax); quote it ("e-4012") or sanitise it, as in exercise 7. -
Open-ended, so no single answer, but expect these classes of failure on real help articles. Queries with several words return nothing when the words live in different articles (FTS5's implicit AND:
warranty refundagainst separate Warranty and Returns articles returns zero rows), so fall back to OR or to a quorum of terms. Plural and tense mismatches under the defaultunicode61tokenizer are fixed byporter unicode61. Identifiers such asE-4012need quoting or a custom tokenizer. User words that the corpus never uses ("money back" vs "refund") need a synonym table likeexpand.py's. Prefix (refund*) and column filters (title:) fix partial words and noisy bodies. Keep a list of the queries that returned nothing: it is your first test set for 06.10. -
Treat
NEAR(a b, N)as "at mostNtokens betweenaandb" (FTS5's meaning, which isabs(pos_a - pos_b) - 1 <= N):python def near_docs(a, b, n): return {d for d in set(postings.get(a, {})) & set(postings.get(b, {})) if any(abs(x - y) - 1 <= n for x in postings[a][d] for y in postings[b][d] if x != y)}Add a
NEAR\(\s*(\w+)\s+(\w+)\s*,\s*(\d+)\s*\)alternative to the tokenizer regex inparse(it must come before the generic[^\s()]+alternative) and an("near", a, b, n)node inev. On the 7-document corpus of 5.1 you should see:NEAR(error checkout, 0)andNEAR(error checkout, 1)return onlyhelp-error-e4012(the body'serrordirectly follows the title's last wordcheckout, so they are 0 tokens apart);NEAR(error checkout, 2)and larger addticket-1042;NEAR(checkout payment, 1)returns nothing andNEAR(checkout payment, 2)returnshelp-error-e4012(itscheckoutat position 15 andpaymentat position 18 have two tokens between them). The exercise's own exampleNEAR(error refund, 5)andNEAR(error refund, 50)both return[], because no document in this corpus contains both words. That is the test that catches an implementation that confuses NEAR with OR. Every case above agrees with SQLite'sNEAR(a b, N)when the title and body are indexed as one column (FTS5 never matches NEAR across two columns, so a table with separatetitleandbodycolumns gives different answers for the title-to-body cases). -
Extract letters and digits, quote each one, and let FTS5 apply its implicit AND:
python import re def sanitize_fts_query(user_input: str) -> str: terms = re.findall(r"[^\W_]+", user_input.casefold()) return " ".join('"' + t + '"' for t in terms)Results (empty string means "skip the query"):
refund" OR 1=1 --becomes"refund" "or" "1" "1"(an ordinary four-term AND that matches nothing, where the raw string fails withunterminated string);"unclosedbecomes"unclosed"(raw:unterminated string);NEAR(becomes"near"(raw:fts5: syntax error);e-4012becomes"e" "4012"and finds an article titledError E-4012(raw:no such column: 4012);title:refundbecomes"title" "refund", so the column filter is gone by design. Anything that reduces to no terms (AND, whitespace, punctuation only) becomes an empty or harmless string, so check for empty and return no results rather than callMATCH '', which is a syntax error. The price of safety is that users lose operators; offer them as separate structured parameters, not by trusting raw text. Note that parameter binding (MATCH ?) already stops SQL injection; this function stops FTS syntax errors and operator abuse, which parameters do not. -
Skeleton: for each question,
hits = [IDS[i] for _, i in bm.search(q, k=5)], thenrecall = len(set(hits) & gold) / len(gold), averaged over questions. Expect most questions that reuse words from the gold chunk (warranty screen,checkout error) to score 1.0, and paraphrases with no shared word to score 0.0: on the 10-document Acme corpus of 3.6,how do I cancel the contractcannot findcontract-termination, whose text saysterminate ... agreement. Look at the ranked lists, not just the score. A paraphrase can score well by accident because this lesson's toy tokenizer keeps stopwords, soforandainmoney back for a broken itemmatch the Returns text even though nothing in the query means "refund". That is also why a 10-document corpus cannot be your baseline: with 3 results out of 10 documents, most queries succeed. Use hundreds of chunks and at least 30 questions, and inspect the rank, not just the hit. The honest result of this exercise is a number and a list of misses sorted by type (paraphrase, identifier, typo), which is what 06.8 fixes.
Check yourself#
- Why does an embedding model rank "error code E-4012" and "error code E-4021" nearly identically, and why does BM25 not?Embeddings compress meaning; similar-looking strings embed nearby because the model can't preserve exact surface form. BM25 matches the literal token
4012/4021— different terms, different postings, exact distinction. - What three things does an inverted index store per term, and what is each used for?Document IDs (which docs contain it), term frequency per doc (score numerator), and positions (phrase/proximity queries). Plus per-doc length and corpus df/avgdl statistics for scoring.
- Why must the same analyser run on documents and queries? What breaks if they differ?Because index terms and query terms must be identical strings to hit the same postings. If the index stores stemmed
runbut the query producesrunning, nothing matches — silently. - What's the difference between stemming and lemmatization, and what's a real failure mode of each?Stemming = rule-based suffix stripping (fast, can collide:
university→univers). Lemmatization = dictionary-based base form (better→good, handles irregulars). Stemming fails by over-merging; lemmatization fails by cost/coverage gaps and by being too precise for recall. - BM25 has two parameters. Name them, give the classic defaults, and say what each controls.
k1(term-frequency saturation; default ~1.2, rank_bm25 ships 1.5) andb(document-length normalization; default 0.75). - Why does Robertson's original IDF go negative, and how do Lucene/Elasticsearch and rank_bm25 handle it differently?Original IDF
ln((N-df+0.5)/(df+0.5))is negative when df > N/2. Lucene/ES useln(1 + ...)keeping it positive; rank_bm25's Okapi floors negative IDFs at epsilon × average IDF. ts_rankin PostgreSQL is not BM25. What is it, and when would you need a real BM25 extension?ts_rank/ts_rank_cdsum lexeme weights (cover density rewards proximity) — no k1/b, no IDF saturation curve. You need pg_search (ParadeDB) or vchord_bm25 when BM25 semantics matter.- SQLite FTS5's
bm25()returns negative scores. What does that mean forORDER BY, and what are k1/b set to?FTS5 negates the score so ascendingORDER BY bm25(t)returns best-first; k1=1.2, b=0.75 are hard-coded. - Name three ways to make a title match count more than a body match, with one engine example each.FTS5
bm25(t, 10.0, 1.0)column weights; Elasticsearchtitle^3field boost or"boost"on amatchclause; BM25F per-field weights (Lucene BM25FSimilarity). - A user searches
E-40expecting every error code that starts withE-40, but gets hundreds of hits. What went wrong?Under this lesson's[a-z0-9]+analysisE-40becomes two terms,eand40. The stray single-lettere(or ane*prefix) matches a large share of the corpus (the 5.1 demo:e*hit 5 of 7 documents), while40matches only the term40, not4012. Index identifiers as whole terms (akeywordfield, or a tokenizer that keeps-) so a prefix query likeE-40*runs over whole identifiers, and give prefix queries a prefix index (2.5) so they stay fast. - Why is
*leadingwildcard or highfuzzinesson an identifier field a production risk?Leading wildcards scan the whole term dictionary; high fuzziness on short/ID terms matches unintended identifiers (E-4012→E-4021) and enables expensive automaton queries — DoS surface. - Your BM25 eval was tuned last quarter; after a corpus re-import, thresholds stopped working. Why, and what should you evaluate instead?IDF and avgdl are corpus statistics — they drift as documents are added, shifting every score. Evaluate rank-based metrics (recall@k, MRR, nDCG) on a fixed query set, not absolute score thresholds.
- SPLADE/BGE-M3 sparse vectors are called "learned lexical" — how do they relate to BM25, and where does the fusion happen?They encode text into sparse vocabulary-weighted vectors with learned term importance and expansion — BM25-shaped scoring over a neural term-weighting function. Fusion with dense happens in 06.8's hybrid layer.
- When is SQLite FTS5 the right production choice, and when is it definitely not?Right: prototypes, CLI tools, embedded/mobile apps, small corpora where a server isn't justified. Wrong: multi-tenant production search needing HA, faceting at scale, complex analysers, or sub-second refresh across a cluster.
Further resources#
- Robertson & Zaragoza, "The Probabilistic Relevance Framework: BM25 and Beyond" (Foundations and Trends in IR, 2009) — the canonical BM25 reference.
- Lv & Zhai, "When Documents Are Very Long, BM25 Fails" (SIGIR 2009) and "Lower-Bounding Term Frequency Normalization" (CIKM 2011) — BM25L and BM25+.
- Robertson, Zaragoza & Taylor, "Simple BM25 Extension to Multiple Weighted Fields" (CIKM 2004) — BM25F.
- Kamphuis et al., "Which BM25 Do You Mean? A Large-Scale Reproducibility Study of Scoring Variants" (ECIR 2020) — why two libraries' BM25 scores for the same query can differ.
- SQLite FTS5 documentation — https://www.sqlite.org/fts5.html — authoritative for bm25(), tokenizers, query syntax, options.
- PostgreSQL Text Search documentation — https://www.postgresql.org/docs/current/textsearch.html — tsvector/tsquery/ts_rank, GIN indexes.
- Elasticsearch "Text analysis" and "Similarity" docs — https://www.elastic.co/docs — analysers, BM25Similarity parameters, match queries.
- OpenSearch keyword search docs — https://docs.opensearch.org/latest/search-plugins/keyword-search/ — similarity algorithms incl. the 3.0 LegacyBM25→BM25 change.
- ParadeDB docs — https://www.paradedb.com/docs — pg_search BM25 in Postgres.
- VectorChord-BM25 — https://github.com/supervc-stack/VectorChord-bm25 — BM25 as a Postgres extension.
- bm25s — https://bm25s.github.io and https://arxiv.org/abs/2407.03618 — fast pure-Python BM25, five variants.
- rank_bm25 — https://github.com/dorianbrown/rank_bm25 — the classic Python implementation.
- tantivy-py — https://github.com/quickwit-oss/tantivy-py — Rust search engine bindings.
- Pyserini — https://github.com/castorini/pyserini — reproducible IR research toolkit.
- whoosh3 — https://pypi.org/project/whoosh3/ — maintained Whoosh continuation.
- Meilisearch typo tolerance docs — https://www.meilisearch.com/docs — FST + Levenshtein automaton details.
- Typesense docs — https://typesense.org/docs — engine comparison and architecture.
- BGE-M3 model card — https://huggingface.co/BAAI/bge-m3 — dense+sparse+multi-vector embeddings; paper arXiv:2402.03216.
- SPLADE — Formal et al., "SPLADE: Sparse Lexical and Expansion Model" (2021) and successors — learned sparse retrieval.
- Apache Lucene documentation — https://lucene.apache.org — the engine underneath Elasticsearch.
← 06.6 — Filtering, Metadata and Multi-Tenant Search | Module 06 overview | 06.8 — Hybrid Search →