TExcelTAD
Home › System Design › Search and Inverted Indexes

Search and Inverted Indexes

WHERE description LIKE '%wireless headphones%' works on a thousand rows and collapses on a hundred million: a B-tree index can't help with words in the middle of text, and SQL has no idea which matching row is the best match. Search engines (Elasticsearch, OpenSearch, Solr, Meilisearch, and Lucene underneath most of them) solve both problems with an inverted index and relevance scoring.

The inverted index

A normal ("forward") index maps a document to its words. An inverted index maps each word (a term) to the list of documents containing it, called a posting list. Finding documents with a word becomes a single dictionary lookup.

python · try it yourself
import re
from collections import defaultdict

docs = {
    1: "Wireless noise-cancelling headphones with 30 hours of battery",
    2: "Wired studio headphones for mixing and mastering",
    3: "Bluetooth speaker, wireless, waterproof, 12 hours battery",
    4: "Noise-cancelling earbuds: wireless and compact",
}

STOP_WORDS = {"with", "of", "for", "and", "the", "a"}

def analyze(text):
    tokens = re.findall(r"[a-z0-9]+", text.lower())          # lowercase + split
    return [t for t in tokens if t not in STOP_WORDS]

index = defaultdict(set)
for doc_id, text in docs.items():
    for term in analyze(text):
        index[term].add(doc_id)

for term in ["wireless", "headphones", "noise", "battery"]:
    print(f"{term:<11} -> {sorted(index[term])}")

def search_all(query):                                       # AND query
    postings = [index[t] for t in analyze(query)]
    return sorted(set.intersection(*postings)) if postings else []

print("wireless headphones ->", search_all("wireless headphones"))
print("noise wireless      ->", search_all("noise wireless"))
wireless    -> [1, 3, 4]
headphones  -> [1, 2]
noise       -> [1, 4]
battery     -> [1, 3]
wireless headphones -> [1]
noise wireless      -> [1, 4]

The analyzer matters as much as the index: lowercasing, splitting on punctuation, removing stop words, and in real engines also stemming (headphones → headphon), synonyms and language-specific rules. The same analyzer must run on documents at index time and on queries at search time.

Ranking with TF-IDF and BM25

Matching is not enough; results must be ranked. Two intuitions drive classic scoring:

  • Term frequency (TF): a document that mentions "battery" three times is probably more about batteries.
  • Inverse document frequency (IDF): a rare term ("waterproof") is more informative than a common one ("wireless").

BM25, the default in Lucene and Elasticsearch, refines TF-IDF: repeated terms help with diminishing returns (k1), and long documents are penalised slightly (b).

python · try it yourself
import math
import re
from collections import Counter

docs = {
    1: "wireless headphones with long battery life and wireless charging case",
    2: "wired headphones",
    3: "wireless speaker waterproof",
    4: "headphones case",
}
tokenized = {d: re.findall(r"[a-z]+", t.lower()) for d, t in docs.items()}
N = len(docs)
avg_len = sum(len(t) for t in tokenized.values()) / N

def idf(term):
    df = sum(term in toks for toks in tokenized.values())
    return math.log(1 + (N - df + 0.5) / (df + 0.5))

def bm25(query, doc_id, k1=1.2, b=0.75):
    toks = tokenized[doc_id]
    tf = Counter(toks)
    score = 0.0
    for term in query.split():
        f = tf[term]
        score += idf(term) * f * (k1 + 1) / (f + k1 * (1 - b + b * len(toks) / avg_len))
    return score

for query in ["wireless headphones", "waterproof", "headphones"]:
    ranked = sorted(docs, key=lambda d: -bm25(query, d))
    scores = ", ".join(f"doc{d}={bm25(query, d):.2f}" for d in ranked if bm25(query, d) > 0)
    print(f"{query!r:<22} {scores}")
'wireless headphones'  doc1=0.92, doc3=0.79, doc2=0.46, doc4=0.46
'waterproof'           doc3=1.37
'headphones'           doc2=0.46, doc4=0.46, doc1=0.23

For "headphones", the short documents 2 and 4 score twice as high as the long document 1, even though all three contain the word once: BM25's length normalisation assumes a match in a short text is more focused.

Scaling a search cluster

text
             query "wireless headphones"
                       |
                [ coordinator ]
           scatter /    |     \ gather top-k from each shard, merge
          [shard 0] [shard 1] [shard 2]     each shard = a Lucene index
          + replica + replica  + replica    replicas serve reads and fail over
  • Documents are sharded (usually by document id); every query goes to all shards (scatter-gather), each returns its top k, and the coordinator merges them.
  • Replicas add read throughput and availability.
  • Indexing is near real-time: new documents become searchable after a periodic refresh (1 s by default in Elasticsearch), when a new immutable segment is written.

Keeping the index in sync

The search index is usually a secondary store, derived from the primary database. Never dual-write from the application (one write can fail); instead stream changes:

python · try it yourself
primary_db = {}
search_index = {}
change_log = []                         # stands in for CDC / an outbox / Kafka

def save_product(pid, title, in_stock):
    primary_db[pid] = {"title": title, "in_stock": in_stock}
    change_log.append(("upsert", pid))

def delete_product(pid):
    primary_db.pop(pid, None)
    change_log.append(("delete", pid))

def indexer(offset):
    for op, pid in change_log[offset:]:
        if op == "delete" or pid not in primary_db:
            search_index.pop(pid, None)
        else:                            # re-read current state: replays are safe
            search_index[pid] = primary_db[pid]["title"].lower().split()
    return len(change_log)

save_product(1, "Desk Lamp", True)
save_product(2, "Floor Lamp", True)
offset = indexer(0)
save_product(1, "LED Desk Lamp", True)
delete_product(2)
print("before indexer catches up:", search_index)
offset = indexer(offset)
print("after:                    ", search_index)
before indexer catches up: {1: ['desk', 'lamp'], 2: ['floor', 'lamp']}
after:                     {1: ['led', 'desk', 'lamp']}

Between the write and the indexer run, search results are stale. That's normal: search is eventually consistent with the database, and product pages should read authoritative data (price, stock) from the primary store, not from the search hit.

Feature Technique
Typo tolerance Edit-distance (fuzzy) matching, n-gram indexes
Autocomplete Prefix indexes / tries / edge n-grams, precomputed popular queries
Facets ("Brand (12)") Aggregations over doc values
Semantic search Vector embeddings + approximate nearest neighbour indexes (HNSW), often combined with BM25 ("hybrid")

Test yourself

What does an inverted index map?

  1. Documents to their words
  2. Each term to the documents that contain it
  3. Users to their queries
  4. Shards to replicas

Why does IDF give 'waterproof' more weight than 'wireless'?

  1. It is a longer word
  2. It appears in fewer documents, so it says more about a match
  3. It comes later in the text
  4. It is in the dictionary

How should a search index usually be kept in sync with the primary database?

  1. The application writes to both in the same request
  2. Stream database changes (CDC/outbox) to an indexer
  3. Rebuild the whole index on every write
  4. Store data only in the search engine