Lexical search & BM25
BM25 ranks documents by how often they contain your query's words, rewarding rare words and discounting long documents. Decades old, no model, and still better than embeddings at exact terms: IDs, error codes, product names.
Analogy: The index at the back of a textbook: look up the rare word, jump straight to the pages that use it. Brilliant for "ERR_1043", useless when the book says "automobile" and you looked up "car".
How it works
- An inverted index maps each term to its documents, so only documents sharing a query word get scored.
- Rare terms weigh most (IDF):
0x80070005in 37 of 200k tickets ≈ 8.6; "error" ≈ 0.7. - Term frequency saturates (
k1= 1.2), andb= 0.75 discounts long documents, which match words by chance. - It misses meaning: "cancel my plan" never matches "terminate subscription", so pair it with vectors.
- Lucene (Elasticsearch, OpenSearch, Solr) uses BM25 by default; Postgres
ts_rankis not BM25, since it ignores IDF.
Check yourself
Answer to mark it learned; your answers aren't scored.
Your team built keyword search with Postgres ts_rank and calls it BM25. For "error 0x80070005", tickets that say "error" many times outrank the few tickets quoting the code. Most likely cause?
Go deeper
Full explanation
BM25 scores a document by the query words it contains. An inverted index maps each term to the documents that contain it, so only documents sharing a word get scored: no model, no GPU.
For each query term, three ingredients combine:
- Inverse document frequency (IDF): rare terms count more. Matching
0x80070005is strong evidence; matching "error" is noise. - Term frequency with saturation: repeats help, with diminishing returns.
k1(default 1.2) sets how fast it saturates, so the 10th mention adds far less than the 2nd. - Length normalization:
b(default 0.75) discounts long documents, which match words by chance.
score = Σ IDF(t) · tf·(k1+1) / (tf + k1·(1 − b + b·len/avg_len))
It wins where embeddings blur: IDs, error codes, SKUs, function names, legal citations, brand-new jargon the embedding model never saw. It loses on meaning ("cancel my plan" does not match "terminate subscription") and it depends on tokenization, stemming and stopwords for each language.
Lucene, under Elasticsearch, OpenSearch and Solr, uses BM25 by default; Tantivy is the Rust equivalent. Postgres ts_rank is not BM25: it ignores IDF.
Code BM25 that keeps error codes intact
import re
from rank_bm25 import BM25Okapi
docs = [
"Error E1043: payment gateway timeout after 30 s",
"How to reset your password",
"Payment failed? Check your card details",
"E1044 means the card was declined by the issuer",
]
def tokenize(text: str) -> list[str]:
# Keep codes like e1043 as one token: embeddings tend to blur them
return re.findall(r"[a-z0-9]+", text.lower())
# Lucene's defaults; rank_bm25 would default k1 to 1.5
bm25 = BM25Okapi([tokenize(d) for d in docs], k1=1.2, b=0.75)
query = "E1043 timeout"
scores = bm25.get_scores(tokenize(query))
for score, doc in sorted(zip(scores, docs), reverse=True)[:2]:
print(f"{score:.2f} {doc}")
# Only the E1043 doc scores; the E1044 doc gets 0, though to an embedding the codes look alikeReal example
An IT help desk has 200k tickets. A user pastes "error 0x80070005 when installing updates". Vector search returns generic "access denied" articles: semantically close, wrong fix. BM25 finds 0x80070005 in only 37 tickets, so its IDF ≈ 8.6, versus ≈ 0.7 for "error", which appears in half the corpus. The 37 exact matches jump to the top, and in a hybrid setup the vector leg still contributes the paraphrased tickets that never quote the code.
Trade-offs +4 · −3
+ You gain
- Nails exact matches: IDs, error codes, SKUs, names, rare jargon.
- No model, no GPU, no embedding drift; indexing is cheap and incremental.
- Explainable: you can show which terms matched and why a document scored.
- Handles brand-new vocabulary on day one, with no retraining.
− You pay
- No semantics: misses synonyms and paraphrases ("cancel" versus "terminate my plan").
- Quality hinges on tokenization, stemming and stopwords, configured per language.
- Weak on long conversational questions where few words carry the intent.
Use it when
Always as one leg of Hybrid search & RRF. On its own when queries are keyword-shaped: codes, identifiers, names, legal or medical terms, logs.
Avoid it when
As the only retriever for conversational questions, cross-lingual search or paraphrase-heavy corpora: pair it with dense vectors.
Numbers to know 4
- Lucene, Elasticsearch and OpenSearch defaults: k1 = 1.2, b = 0.75.
- BM25 has been Lucene's default similarity since Lucene 6.0 (2016).
- IDF ≈ ln(1 + (N − n + 0.5)/(n + 0.5)): a term in 37 of 200k docs ≈ 8.6; in half the docs ≈ 0.7.
- BEIR (18 datasets, 2021): out of domain, BM25 was a strong zero-shot baseline that many dense retrievers of the time failed to beat.
Common pitfalls 4
- Calling Postgres
ts_rankBM25: it has no IDF. Use a BM25 extension such as ParadeDB's pg_search, or a Lucene-based engine. - Default analyzers that split or mangle identifiers like
v2.3.1orERR-1043. Test your real codes through the analyzer. - English stemming and stopwords applied to Spanish or mixed-language content.
- Comparing or adding raw BM25 scores across queries: they are unbounded and not probabilities.
Interview questions 2
Answer out loud first, then reveal.
If embeddings understand meaning, why keep BM25?Show answer
Because the failure modes are complementary. An embedding compresses a chunk into ~1,000 dimensions, and rare exact tokens, like an error code, a SKU or a customer's name, get blurred into "something similar". BM25 rewards exactly those rare tokens through IDF. The queries users complain about most are often exact-match ones, so I run both and fuse them with RRF. It is cheap, needs no GPU, and when someone asks why a document ranked, I can show the matched terms.
What do k1 and b do, and would you tune them?Show answer
k1 controls term-frequency saturation: at 0 frequency is ignored, and higher values let repeated terms keep adding score; Lucene uses 1.2. b controls length normalization, from 0 (none) to 1 (full); the default is 0.75. I rarely tune them first: analyzers, synonyms and field boosts, like title over body, move results more. If I do tune them, it is on a labeled query set with nDCG@10, for example lowering b when long documents are genuinely more relevant.