← Back to System Design, page 5

system-design-0095 · Medium fresher

How does full-text search work? Explain inverted indexes, tokenisation and BM25 ranking with a small example.

An inverted index maps each term to the list of documents that contain it (a posting list), often with positions and counts, so a query looks up a few lists instead of scanning every document. Text is tokenised and normalised (lowercase, remove punctuation, sometimes stem words) the same way at index and query time. BM25 scores each matching document higher when query terms appear often in it, rarer terms count more, and long documents are normalised so they do not win only by length.

Full answer

Inverted index

Documents:

  1. "binary search on a sorted array"
  2. "binary search tree insert and delete"
  3. "sorting an array with merge sort"

The index maps term to postings:

  • binary to {1, 2}
  • search to {1, 2}
  • array to {1, 3}
  • sort (after stemming "sorting" and "sorted") to {1, 3}

A query for "binary array" fetches two posting lists and combines them: intersection for AND (doc 1), union for OR (docs 1, 2, 3). Posting lists are sorted by document ID and compressed, so merging is fast even with millions of entries. Storing positions enables phrase queries ("binary search" as adjacent words).

Analysis (tokenisation)

The same analyser runs on documents and queries:

  1. Split text into tokens.
  2. Lowercase, remove accents, drop very common stop words if desired.
  3. Stem or lemmatise ("searching" to "search").
  4. Language-specific steps; for Hindi or Japanese text, tokenisation rules differ (character n-grams or dictionary-based segmentation).

If analysis differs between indexing and querying, matches are missed.

BM25 ranking

For each query term t in document d:

score += IDF(t) x tf x (k1 + 1) / (tf + k1 x (1 - b + b x len(d) / avg_len))

  • tf (term frequency): more occurrences raise the score, but with diminishing returns controlled by k1 (about 1.2).
  • IDF: terms in fewer documents are more informative; "the" adds almost nothing, "dijkstra" adds a lot.
  • Length normalisation (b about 0.75): a match in a short title-like document counts more than in a long page.
python
import math
from collections import Counter, defaultdict

docs = {
    1: "binary search on a sorted array",
    2: "binary search tree insert and delete",
    3: "sorting an array with merge sort",
    4: "search engine ranking with bm25",
}

index = defaultdict(dict)                 # term -> {doc_id: term frequency}
lengths = {}
for d, text in docs.items():
    words = text.split()
    lengths[d] = len(words)
    for term, tf in Counter(words).items():
        index[term][d] = tf
avg_len = sum(lengths.values()) / len(lengths)


def bm25(query, k1=1.2, b=0.75):
    n = len(docs)
    scores = defaultdict(float)
    for term in query.split():
        postings = index.get(term, {})
        idf = math.log(1 + (n - len(postings) + 0.5) / (len(postings) + 0.5))
        for d, tf in postings.items():
            norm = tf + k1 * (1 - b + b * lengths[d] / avg_len)
            scores[d] += idf * tf * (k1 + 1) / norm
    return sorted(scores.items(), key=lambda x: -x[1])


if __name__ == "__main__":
    ranked = bm25("binary search array")
    assert ranked[0][0] == 1                       # has all three terms
    assert {d for d, _ in ranked} == {1, 2, 3, 4}
    assert bm25("heap") == []
    print("ok:", [(d, round(s, 3)) for d, s in ranked])

Save as bm25.py and run python3 bm25.py (Python 3.13.5).

This snippet skips stemming for brevity, so "sorting" and "sorted" are different terms here.

In practice

Search engines such as Elasticsearch, OpenSearch and Solr (built on Lucene) store indexes in immutable segments, merge them in the background, and shard the index across nodes; each shard answers queries and a coordinator merges the top results. BM25 is often the first stage, followed by a re-ranker that uses more signals (popularity, freshness, personalisation, learned models).

By level

Fresher: Explain that the index lists, for each word, which documents contain it, like the index at the back of a book. A fresher should show how a two-word query is answered.

Mid: Describe analysis, posting list merging and the parts of BM25, with the small example. Mention phrase queries.

Senior: Discuss segments and merging, sharding and top-k merging, multilingual analysis, typo tolerance and two-stage ranking. Expect clear reasoning about relevance trade-offs.

Key points

  • Inverted index maps terms to sorted, compressed posting lists
  • Same analysis at index and query time
  • AND intersects posting lists; OR unions them
  • BM25 combines term frequency with saturation, IDF and length normalisation
  • Shard indexes and re-rank top results with extra signals

Common mistakes

  • Scanning documents with LIKE '%term%' at scale
  • Using different analysers for indexing and querying
  • Thinking raw term counts alone give good ranking
  • Ignoring language-specific tokenisation

Follow-ups

  • How do phrase queries use positions?
  • How would you support typo tolerance?
  • How do you keep the index updated when documents change?

Tips

  • Build a tiny index by hand
  • Explain each part of BM25 in words
  • Mention analysis consistency

Evaluation rubric

  • Correct inverted index explanation
  • Tokenisation and normalisation understood
  • BM25 components explained
  • Awareness of real search systems