System design concepts · Specialized Building Blocks

Designing Search: Inverted Index, Elasticsearch and Ranking

Databases answer "give me the row with this ID". Search engines answer "find me the things that best match these words", and that needs a completely different data structure.

What you'll be able to explain
  • Explain the inverted index and text analysis
  • Describe relevance scoring (BM25) and ranking layers
  • Shard and replicate a search cluster
  • Keep a search index in sync with the source of truth
  • Know where vector/semantic search fits

The inverted index

A book index maps words to pages. An inverted index maps terms to the documents containing them (a postings list), often with positions and frequencies.

CLIENTDoc 1"paneer butter masala"CLIENTDoc 2"butter chicken"CLIENTDoc 3"palak paneer"WORKERAnalyzerlowercase, stem, tokensDATABASEpaneer → 1, 3DATABASEbutter → 1, 2DATABASEchicken → 2
Indexing turns documents into terms; queries intersect postings lists.

A query for "butter paneer" looks up both postings lists and intersects (AND) or unions (OR) them, then scores the results.

Text analysis

Before indexing (and querying), text runs through an analyzer:

  1. Tokenise: split into words.
  2. Normalise: lowercase, strip accents.
  3. Remove stop words (optional): "the", "a".
  4. Stem / lemmatise: "running" → "run".
  5. Synonyms: "tv" ↔ "television"; regional terms ("curd" ↔ "dahi").
  6. N-grams for partial matching and typo tolerance; edge n-grams for prefix search.

Indexing and querying must use compatible analyzers, or nothing matches.

Relevance

BM25, the default in Elasticsearch/OpenSearch/Lucene, scores a document higher when:

  • the term appears often in this document (term frequency, with diminishing returns);
  • the term is rare across all documents (inverse document frequency);
  • the document is short (a match in a title beats a match in a 5,000-word page).

Real products layer more on top: field boosts (title > description), business signals (popularity, ratings, availability, distance), personalisation, and often a two-stage ranking: a fast first stage retrieves ~1,000 candidates, then a learned ranking model re-orders the top 100.

Architecture of a search cluster

  • An index is split into shards (each a self-contained Lucene index) and each shard has replicas.
  • A query goes to a coordinating node, which fans out to one copy of every shard (scatter), then merges the top results (gather).
  • More shards → more parallel indexing; more replicas → more query throughput and fault tolerance.
  • Near-real-time: new documents become searchable after a refresh (typically ~1 s).