A search system finds the documents that match a free-text query and ranks them by relevance in milliseconds, across millions or billions of records. Its core data structure is the inverted index, which maps every word to the documents that contain it. Engines such as Elasticsearch, OpenSearch and Solr (all built on Apache Lucene) add text analysis, BM25 ranking and horizontal scaling on top.
Think of it like
The index at the back of a textbook
To find every page that mentions "photosynthesis", you do not read the book cover to cover. You flip to the index, find the word, and read off the page numbers. A search engine builds exactly that index for every word in every document, then adds a judge who decides which of those pages you most likely wanted first.
Why LIKE '%term%' doesn't scale
SELECT id, title
FROM products
WHERE description LIKE '%wireless headphones%';- Full scan: a B-tree index can serve a prefix match (
LIKE 'wire%'), but a leading wildcard forces the database to read every row's text on every query. - No ranking: rows come back in arbitrary order; nothing says which product is the best match.
- Exact substrings only: it misses "headphones wireless", "Wireless Headphone" and "wirless".
- No language awareness: "running" does not match "run", and "café" does not match "cafe".
Catalog
100M rows
about 1 KB of text each
Scanned per query
~100 GB
LIKE with a leading wildcard
Full scan time
tens of s
even at several GB/s
Inverted index lookup
~10 ms
read only the matching postings
The inverted index
A forward index maps documents to words (what a database row is). An inverted index flips it: for every term, store a postings list of the documents that contain it, sorted by document ID, usually with the term frequency and the positions where it occurs. Watch it being built in the simulation above.
D1: "The quick brown fox"
D2: "Quick brown dogs jump"
D3: "The lazy dog sleeps"| Term (after analysis) | Postings: doc @ positions |
|---|---|
brown | D1 @ 2, D2 @ 1 |
dog | D2 @ 2, D3 @ 2 |
fox | D1 @ 3 |
jump | D2 @ 3 |
lazy | D3 @ 1 |
quick | D1 @ 1, D2 @ 0 |
sleep | D3 @ 3 |
quick AND dog: intersect{D1, D2}with{D2, D3}to get{D2}.quick OR dog: union gives{D1, D2, D3}; D2 matches both terms, so it should rank first.- Phrase
"brown dogs": both terms are in D2, anddog(position 2) directly followsbrown(position 1), so D2 matches the phrase.
Making postings fast and small
Because postings lists are sorted, intersecting two lists of sizes m and n is a linear merge, O(m + n), and skip pointers let the merge jump over long runs, so engines start with the rarest term. Lists are compressed by storing gaps between doc IDs (delta encoding) packed into small integers; Lucene encodes blocks of 128 gaps with frame-of-reference bit packing. The term dictionary itself is stored as a finite-state transducer, which makes prefix, wildcard and fuzzy term lookups efficient.
The analysis pipeline
Before text is indexed it passes through an analyzer, which turns raw strings into normalized terms. The same analyzer (or a compatible one) must run on the query, otherwise a search for "Running" will never match the indexed term "run".
- 1
Character filters
Clean the raw text: strip HTML tags, map characters (
&toand), normalize Unicode. - 2
Tokenizer
Split into tokens. The standard tokenizer follows Unicode word-boundary rules; others split on whitespace, produce n-grams or segment Chinese and Japanese text with dictionaries.
- 3
Lowercase
"RUNNING" and "Running" become "running".
- 4
ASCII / accent folding
"café" becomes "cafe" so users without accented keyboards still match.
- 5
Stop words (optional)
Remove very common words such as "the", "a" and "was". Modern engines often keep them, because BM25 already discounts them and phrases like "to be or not to be" need them.
- 6
Stemming or lemmatization
Reduce words to a root: Porter stemming maps "running" to "run" and "runners" to "runner". Lemmatization uses a dictionary to map "better" to "good".
- 7
Synonyms
Expand or map equivalents: "laptop" and "notebook", "tv" and "television".
| Stage | Tokens |
|---|---|
| Input | The Runners' café was RUNNING! |
| Tokenize | The Runners café was RUNNING |
| Lowercase | the runners café was running |
| ASCII folding | the runners cafe was running |
| Stop words | runners cafe running |
| Porter stemming | runner cafe run |
Scoring relevance: TF-IDF and BM25
Matching finds candidates; scoring orders them. Three intuitions drive almost every lexical ranking function:
- Term frequency (TF): a document that mentions "kafka" five times is probably more about Kafka than one that mentions it once, with diminishing returns.
- Inverse document frequency (IDF): rare terms carry more information. Matching "kafka" means a lot; matching "the" means almost nothing.
- Length normalization: one mention in a 10-word title is stronger evidence than one mention in a 10,000-word manual.
TF-IDF
With N = 1,000,000 documents and base-10 logs: "the" appears in 900,000 documents, so its IDF is log(1.11) ≈ 0.05; "kafka" appears in 1,000, so its IDF is log(1,000) = 3. One occurrence of "kafka" outweighs fifty occurrences of "the".
BM25
BM25 (Okapi Best Matching 25) refines TF-IDF and has been the default similarity in Lucene and Elasticsearch since version 5.0. It saturates term frequency, so the 50th repetition adds almost nothing, and it normalizes for document length with a tunable strength.
| Term frequency f | Raw TF (TF-IDF) | BM25 TF part (k₁ = 1.2, b = 0) |
|---|---|---|
| 1 | 1 | 1.00 |
| 2 | 2 | 1.38 |
| 5 | 5 | 1.77 |
| 10 | 10 | 1.96 |
| 100 | 100 | 2.17 (limit is k₁ + 1 = 2.2) |
- k₁
- Controls how quickly term frequency saturates. Higher values let repeated terms keep adding score for longer; 0 ignores TF entirely.
- b
- Controls length normalization, from 0 (none) to 1 (full). Lower it for fields where length does not signal dilution, such as titles.
Elasticsearch architecture
- Index
- A logical collection of documents with a mapping (schema), such as
products. - Shard
- A self-contained Lucene index holding part of an index's documents. The number of primary shards is set at creation.
- Replica shard
- A copy of a primary on a different node. Replicas provide failover and extra read (search) capacity.
- Node roles
- Master-eligible nodes manage cluster state; data nodes store shards and execute queries; coordinating nodes route requests and merge results; ingest nodes run preprocessing pipelines.
- Segment
- An immutable mini-index inside a shard. A shard is a set of segments that are searched together.
- Translog
- A per-shard write-ahead log that makes acknowledged writes durable before they are committed to segments on disk.
A document is routed to a shard with shard = hash(_routing) % number_of_primary_shards, where _routing defaults to the document ID. Because the formula depends on the primary count, changing it means reindexing (or using the split and shrink APIs). Searches, by contrast, go to every shard, since any shard may hold matches.
products with 3 primary shards (P0 to P2) and 1 replica each (R0 to R2), spread so no node holds both copies of a shard. Pick a flow above to animate a request.Near-real-time search: segments and refresh
- 1
Buffer + translog
A new document goes into an in-memory buffer and is appended to the translog for durability.
- 2
Refresh (every 1 s by default)
The buffer is written as a new immutable segment to the file-system cache and opened for search. This is why Elasticsearch is called near-real-time.
- 3
Flush
Periodically, a Lucene commit fsyncs segments to disk and the translog is trimmed.
- 4
Merge
Background merges combine many small segments into fewer large ones and physically drop deleted documents.
Segments are immutable, so an update is really "mark the old version deleted, index a new one". Immutability makes segments easy to cache and safe to read concurrently. For bulk loads, raise refresh_interval (or set it to -1) and drop replicas temporarily; indexing throughput goes up substantially.
Query types
| Query | What it does | Example use |
|---|---|---|
match | Analyzes the input and finds documents containing the terms (OR by default) | Free-text search box |
multi_match | match across several fields with per-field boosts | Search title^3 and description |
match_phrase | Terms must appear adjacent and in order (uses positions) | "noise cancelling" |
term / terms | Exact, unanalyzed value on a keyword field | brand = acme, status = active |
range | Numeric or date bounds | Price below 200, last 7 days |
bool | Combines clauses: must, should, must_not, filter | Almost every real query |
fuzzy | Matches within a Levenshtein edit distance (at most 2) | Typo tolerance: "hedphones" |
prefix / wildcard | Pattern matches on terms | SKU lookups (use sparingly) |
| Aggregations | Facet counts, histograms, statistics over the matches | "Brand (12)", price buckets |
{
"query": {
"bool": {
"must": [
{
"multi_match": {
"query": "wireless headphones",
"fields": ["title^3", "description"],
"fuzziness": "AUTO"
}
}
],
"filter": [
{ "term": { "brand": "acme" } },
{ "range": { "price": { "lte": 200 } } }
],
"should": [{ "match_phrase": { "title": "noise cancelling" } }]
}
},
"aggs": { "by_brand": { "terms": { "field": "brand" } } },
"size": 10
}Keeping the index in sync with the primary database
The search index is a derived store: the database remains the source of truth, and the index is a read-optimized projection of it. The design question is how changes flow from one to the other.
Dual writes
- The app writes to the DB, then to Elasticsearch
- If the second write fails, the stores silently diverge
- Two concurrent updates can land in different orders in each store
- Simple to start, painful to keep correct
Change data capture (CDC)
- A connector (e.g. Debezium) tails the DB's WAL or binlog
- Every committed change becomes an event, in commit order
- Events flow through Kafka to an indexer that updates the index
- Reliable and replayable; adds a pipeline to operate
Periodic batch reindex
- Rebuild or bulk-update the index on a schedule
- Simple and self-healing
- Results are stale between runs
- Often combined with CDC as a backfill
- Zero-downtime reindexing: build
products_v2with the new mapping, backfill it while CDC keeps both current, then switch theproductsalias atomically. - Never use the search engine as the primary database: it lacks transactions and durable guarantees comparable to an RDBMS, and mappings can force full reindexes.
- Use Message Queues & Pub/Sub for the change stream so the indexer can fall behind and catch up without losing events.
Relevance tuning
- Field boosts: a match in
titleis worth more than indescription(title^3). - Phrase and proximity boosts: reward documents where query terms appear close together.
- Business signals: blend in popularity, ratings, recency decay or distance with
function_score. - Synonyms and spelling: synonym filters,
fuzziness: AUTOand "did you mean" suggestions reduce zero-result searches. - Personalization and learning to rank: re-rank the top few hundred hits with a model trained on clicks and purchases.
- 1
Build a judgment list
Collect representative queries with graded relevant results, from experts or click logs.
- 2
Measure offline
Compute metrics such as NDCG@10, precision@k and MRR for the current configuration.
- 3
Change one thing
Adjust a boost, analyzer or synonym list and re-measure, so you know which change helped.
- 4
A/B test online
Ship to a slice of traffic and watch click-through rate, zero-result rate and conversion.
Implementation
A minimal in-memory search engine: analyze, build postings with term frequencies, then score candidates with BM25.
import math
import re
from collections import Counter, defaultdict
STOP_WORDS = {"a", "an", "and", "the", "of", "to", "is", "in", "was"}
def analyze(text: str) -> list[str]:
tokens = re.findall(r"[a-z0-9]+", text.lower()) # tokenize + lowercase
return [t for t in tokens if t not in STOP_WORDS] # stop words (no stemming here)
class SearchIndex:
def __init__(self, k1: float = 1.2, b: float = 0.75):
self.k1, self.b = k1, b
self.postings: dict[str, dict[int, int]] = defaultdict(dict) # term -> {doc: tf}
self.doc_len: dict[int, int] = {}
def add(self, doc_id: int, text: str) -> None:
terms = analyze(text)
self.doc_len[doc_id] = len(terms)
for term, tf in Counter(terms).items():
self.postings[term][doc_id] = tf
def search(self, query: str, k: int = 10) -> list[tuple[int, float]]:
n = len(self.doc_len)
avgdl = sum(self.doc_len.values()) / max(n, 1)
scores: dict[int, float] = defaultdict(float)
for term in set(analyze(query)):
docs = self.postings.get(term)
if not docs:
continue
idf = math.log(1 + (n - len(docs) + 0.5) / (len(docs) + 0.5))
for doc_id, tf in docs.items():
norm = self.k1 * (1 - self.b + self.b * self.doc_len[doc_id] / avgdl)
scores[doc_id] += idf * tf * (self.k1 + 1) / (tf + norm)
return sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:k]
idx = SearchIndex()
idx.add(1, "The quick brown fox")
idx.add(2, "Quick brown dogs jump over the quick fox")
idx.add(3, "The lazy dog sleeps")
print(idx.search("quick fox"))
# Doc 1 ranks above doc 2: both contain both terms, but doc 1 is much shorter
# (length normalization outweighs doc 2's second "quick"). Doc 3 does not match.Key takeaways
LIKE '%term%'scans every row and cannot rank; an inverted index maps each term to the documents containing it.- Analyzers (tokenize, lowercase, fold, stop words, stem, synonyms) must be consistent between indexing and querying.
- BM25 improves on TF-IDF with term-frequency saturation and tunable length normalization (k₁ = 1.2, b = 0.75).
- Elasticsearch splits an index into primary shards with replicas; searches scatter to every shard and merge the top hits.
- New documents become searchable after a refresh (1 s by default), which is why search is near-real-time.
- Keep the database as the source of truth and feed the index via CDC rather than dual writes.
Common pitfalls
- Using the search engine as the primary data store.
- Dual writes from the application, which silently diverge on partial failures.
- Running a
termquery against an analyzedtextfield (it looks for the raw, unanalyzed value and finds nothing). - Oversharding: hundreds of tiny shards that waste memory and slow every search.
- Deep pagination with large
fromvalues instead ofsearch_after.
Interview tips
- Draw the inverted index for two or three short documents; it makes the rest of the discussion concrete.
- Know the BM25 intuitions (TF saturation, IDF, length normalization) even if you do not recite the formula.
- Explain query-then-fetch across shards and why deep pagination is costly.
- Describe CDC-based indexing and the resulting freshness lag as a deliberate trade-off.
Real-world applications
- E-commerce product search with facets and typo tolerance.
- Log search and observability (the ELK / OpenSearch stack).
- Site and documentation search, enterprise document search.
- Autocomplete and query suggestions.
- Retrieval for recommendation and RAG pipelines (hybrid lexical plus vector search).
Test yourself
Why does WHERE description LIKE '%headphones%' perform poorly on a large table?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.