Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 28/ 160
02. RAG

BM25 Keyword Search

Classic lexical ranking that shines on exact identifiers, rare terms, and short queries.

BeginnerTF-IDF Family · Exact Match3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

It scores documents by how many times they contain the words you typed, giving extra credit for rare words and not letting very long documents win unfairly.

Think of it like…

The index at the back of a textbook: look up the exact word and see which pages mention it, where a rare word like "photosynthesis" is a much stronger clue than "the", and a page that mentions it ten times beats one that mentions it once, up to a point.

Where you’ve seen it

A developer-docs search handles the query ECONNRESET timeout 30s. Dense retrieval returns general articles about network timeouts, while BM25 puts the troubleshooting page containing the literal "ECONNRESET" first because that token is rare across the corpus (high IDF). The team keeps BM25 in the pipeline and fuses it with vectors, raising recall@10 on error-code queries from 58 to 94 percent.

Words you’ll hear

Inverted index
Map from each term to the documents (and positions) containing it.
IDF
Inverse document frequency: rarer terms contribute more to the score.
k1 and b
BM25 parameters controlling term-frequency saturation (≈ 1.2) and length normalisation (≈ 0.75).
Analyzer
Text processing before indexing: tokenisation, lowercasing, stemming, stop words.

Visual diagram

Loading interactive diagram

Theory & deep dive

The scoring idea

For each query term t, BM25 adds IDF(t) × [tf × (k1 + 1)] / [tf + k1 × (1 − b + b × len/avglen)], where tf is the term's count in the document and len/avglen compares the document's length with the average. IDF is high for rare terms ("ECONNRESET") and near zero for common ones ("the"). The term-frequency part saturates: going from 1 to 3 mentions helps a lot, from 10 to 12 barely. The b parameter penalises long documents (which mention many words by chance); k1 sets how fast saturation happens. Defaults k1 ≈ 1.2 and b ≈ 0.75 work well for most text.

Because scoring needs only the posting lists of the query terms, BM25 is extremely fast on millions of documents, and scores can be explained term by term (useful for debugging relevance). It also works on any language with a suitable analyzer.

Why rare terms dominate

In 1M documents, "timeout" appears in 200,000 (IDF ≈ 1.6) while "ECONNRESET" appears in 40 (IDF ≈ 10). A page mentioning ECONNRESET once outscores one mentioning timeout five times.

Key takeaway: Rare terms, saturated frequency and length normalisation, on an inverted index.

Strengths, weaknesses and tuning

BM25 shines for exact identifiers, product codes, names, quoted phrases, acronyms and short keyword queries, needs no training data, updates instantly as documents change, and costs little. It fails on vocabulary mismatch (the query says "laptop won't start", the page says "notebook fails to boot"), paraphrase and questions phrased in natural language, which is where embeddings help.

Analysis choices matter more than the formula. Use the same analyzer for indexing and querying; stemming improves recall ("running" → "run") but can hurt precision for codes, so keep a non-stemmed field for identifiers; keep or split on punctuation sensibly ("node.js", "C++", "ERR_4012"); add synonyms for domain jargon; apply field boosts (title ×3 over body); and index fields separately (BM25F style). Evaluate with real queries, track zero-result queries, and consider learned sparse models such as SPLADE if you need semantic expansion with an inverted index.

A multi-field query (Elasticsearch-style)

{"multi_match": {"query": "ECONNRESET timeout", "fields": ["title^3", "body", "error_codes.keyword^5"]}} boosts title matches, and matches exact codes in an un-analysed field.

Key takeaway: Great for exact matches; weak on synonyms; analyzers and field boosts matter.

How it works, step by step

Step 1 of 4
Index design

1. Choose analyzers per field

Use stemming for prose fields and exact (keyword) fields for codes, SKUs and names.

body: english · error_code: keyword
Key numbers at this step
Same
analyzer at query time

When to use it & trade-offs

What it is

BM25 is the standard lexical ranking function: it scores a document higher when it contains the query's words more often (term frequency, with diminishing returns), when those words are rare across the collection (inverse document frequency), and it normalises for document length. It runs on an inverted index (word → list of documents), needs no training, and is the default in Elasticsearch, OpenSearch, Lucene, Solr and PostgreSQL full-text extensions. It excels at exact identifiers, error codes, names and short queries, where embeddings are weakest.

Why it matters: Many teams jump to vector search and forget that exact matching still matters: a user typing "ERR_4012", a SKU, a person's surname or a legal section number needs the document containing that exact string, and dense embeddings may not rank it first. BM25 is fast, cheap, explainable and a strong baseline; in a hybrid system it covers precisely what vectors miss.

When to reach for it

  • Searching error codes, SKUs and legal section numbers
  • Baseline retrieval before adding embeddings
  • The sparse half of a hybrid pipeline

When to avoid or be careful

  • Using stemming on identifier fields
  • Different analyzers at index and query time
  • Relying on BM25 alone for conversational questions

Lexical vs semantic retrieval

BM25 (lexical)
Best for: Exact identifiers, names, rare terms, short queries

Strengths: Fast, cheap, explainable, no training; instant updates.

Watch out: No synonym or paraphrase understanding.

Dense embeddings (semantic)
Best for: Natural-language questions and paraphrases

Strengths: Matches meaning across different wording.

Watch out: Weak on exact tokens; needs a model and vector index.

Hybrid (BM25 + dense)
Best for: Most production search and RAG

Strengths: Covers both exact and semantic matches.

Watch out: Two retrievers and a fusion step to tune.

Interview signals & numbers to know

When this topic comes up

  • “Search fails on exact product codes”
  • “What is TF-IDF vs BM25?”
  • “Users search for error messages”
  • Elasticsearch relevance
  • Hybrid retrieval

Benchmarks & rules of thumb

1.2 -
typical k1
0.75 -
typical b
58% → 94% -
error-code recall@10 with hybrid in the example

Common mistakes & follow-ups

Common interview mistakes

  • Stemming product codes so "ABC-100" and "ABC-10" blur together.
  • Indexing with one analyzer and querying with another, so terms never match.
  • Dropping keyword search entirely after adding embeddings and losing exact-match queries.

Likely interviewer follow-ups

  • How does BM25 differ from TF-IDF?
  • Why does BM25 beat embeddings on error codes?
  • How would you handle synonyms in a BM25 system?
Interview tip: Give a rare-term example (an error code) to show why IDF matters. A concrete query makes lexical search's value obvious.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply BM25 Keyword Search with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Metadata Filtering
Next topic
Hybrid Search