Search and the Inverted Index
How full-text search engines find and rank documents fast, and how to keep them in sync.
What is it?
A database is great at "find the row with id 42" or "orders where status = shipped". It's bad at "find products whose description mentions wireless noise-cancelling headphones", especially with typos, plurals and ranking by relevance. A LIKE '%headphones%' query has to scan every row.
Search engines solve this with an inverted index: instead of mapping each document to its words, they map each word to the list of documents that contain it. Finding documents for a query becomes a few fast lookups.
Then they rank results using scoring formulas like TF-IDF or BM25, which favor documents where query words appear often, and words that are rare across the collection.
Systems like Elasticsearch and OpenSearch (built on the Lucene library) wrap this in a distributed service. Usually they're a secondary store, kept in sync with the main database.
Explain like I'm 10
An inverted index is the index at the back of a textbook. Instead of reading every page to find 'photosynthesis', you look up the word and get the page numbers directly.
Examples
Building a tiny inverted index
const documents = {
1: "Wireless headphones with noise cancelling",
2: "Wired headphones for studio use",
3: "Wireless charger",
};
function tokenize(text) {
return text.toLowerCase().split(/\W+/).filter(Boolean);
}
const invertedIndex = new Map(); // term -> Set of document ids
for (const [id, text] of Object.entries(documents)) {
for (const term of tokenize(text)) {
if (!invertedIndex.has(term)) invertedIndex.set(term, new Set());
invertedIndex.get(term).add(Number(id));
}
}
// Query "wireless headphones": intersect the posting lists (AND)
const wireless = invertedIndex.get("wireless"); // {1, 3}
const headphones = invertedIndex.get("headphones"); // {1, 2}
const matches = [...wireless].filter((id) => headphones.has(id)); // [1]Each term maps to a posting list of documents. A multi-word query is a set intersection (AND) or union (OR) of small lists, never a scan of all documents.
How it works
1. Analysis (tokenization). Text is run through an analyzer: split into tokens, lowercased, and optionally stemmed ("running" -> "run"), with stop words removed and synonyms added. The same analyzer must run on queries, or "Running" in a query won't match "run" in the index.
2. Inverted index. For each term, store a posting list: the document ids containing it, often with term frequency and positions (for phrase queries). Lists are sorted and compressed so intersections are fast.
3. Ranking. - TF-IDF: term frequency (how often the term appears in this document) times inverse document frequency (rarer terms across the collection count more). "the" is everywhere and worth little; "noise-cancelling" is rare and worth a lot. - BM25, the default in Lucene-based engines, refines this: repeated terms give diminishing returns (saturation), and scores are normalized by document length so long documents don't win just by being long.
4. Distributed architecture (Elasticsearch-style). An index is split into shards, each a self-contained Lucene index, with replica shards for availability and read throughput. A query goes to a coordinating node, fans out to one copy of every shard, each shard returns its top results, and the coordinator merges them (then fetches the full documents). Writes become searchable after a periodic refresh (1 second by default), so search is near-real-time. Lucene writes immutable segments and merges them in the background; deletes are marked and cleaned up during merges.
5. Keeping the index in sync. The database stays the source of truth. Writing to both the database and the search engine from app code (dual writes) drifts when one write fails. Better: change data capture (CDC), where a tool such as Debezium reads the database's replication log and streams changes through a queue such as Kafka to an indexer. Or use the outbox pattern. Keep a way to reindex from scratch, since mappings and analyzers change.
Inverted index
term posting list (doc ids)
"wireless" -> [1, 3]
"headphones" -> [1, 2]
"charger" -> [3]
Sync and query path
App --write--> Primary DB --replication log--> CDC (e.g. Debezium) --> Kafka --> Indexer
|
User --search--> Search API --> Coordinator node --> Shard 1 (top 10) -----------+
| --> Shard 2 (top 10) |
| --> Shard 3 (top 10) index writes
<-- merge to global top 10, fetch docsWhy does it exist?
Users expect search that's fast, forgiving of word forms and typos, and ranked by relevance. Relational indexes (B-trees) match exact values or prefixes, not words inside text, and have no notion of relevance. Inverted indexes and scoring functions were built precisely for this.
When to use it
Use a search engine for full-text search over product catalogs, documents, logs, help articles or messages; for faceted filtering ("brand: Sony, price under $200") combined with text; and for autocomplete and fuzzy matching.
When not to use it
Don't use a search engine as your primary database: it's eventually consistent with your writes and not built for transactions. For small datasets or simple needs, your database's built-in full-text search (PostgreSQL tsvector, MySQL FULLTEXT) may be enough and avoids running a second system. For exact lookups by key, a normal index is simpler and faster.
Common mistakes
Writing to the database and the search index separately in app code, so the two silently drift apart on partial failures.
Using different analyzers at index time and query time, so obvious matches are missed.
Choosing a shard count without planning; in Elasticsearch the primary shard count is fixed at index creation, and changing it means reindexing (or the split/shrink APIs).
Expecting a document to be searchable immediately after writing it, ignoring the refresh interval.
Using deep pagination (page 10,000) with from/size, which forces every shard to collect and sort huge result sets.
Practice exercises
- Easy:
Build the inverted index by hand for three short sentences, then answer the query 'quick AND fox'.
- Medium:
Explain why BM25 ranks a short product title containing 'headphones' once above a 5,000-word review containing it three times.
- Hard:
Design search for an e-commerce site with 50 million products: indexing pipeline, sync from PostgreSQL, shard sizing, reindexing with zero downtime, and handling of price updates every few seconds.
Interview questions
What is an inverted index?
A map from each term to the list of documents (and often positions) containing it. Queries look up terms and combine their posting lists instead of scanning every document.
Why is LIKE '%word%' slow in a relational database?
A leading wildcard can't use a B-tree index, which is ordered by the value's prefix, so the database scans every row. It also has no stemming, typo tolerance or relevance ranking.
What does tokenization or analysis do?
Converts raw text into searchable terms: splitting into tokens, lowercasing, removing stop words, stemming and adding synonyms. Queries must use the same analysis as indexing so terms match.
Explain TF-IDF in one sentence.
A term scores higher in a document the more often it appears there (term frequency) and the rarer it is across all documents (inverse document frequency).
How does BM25 improve on TF-IDF?
It saturates term frequency, so the tenth occurrence adds much less than the first, and normalizes by document length relative to the average, so long documents don't win just by containing more words.
How does a distributed search query execute?
A coordinating node sends the query to one copy (primary or replica) of every shard. Each shard returns its top-k ids and scores, the coordinator merges them into a global top-k, then fetches the full documents for just those results.
Why is Elasticsearch called near-real-time?
New writes go to an in-memory buffer and become searchable only when a refresh creates a new segment, every second by default. So there's a short delay between indexing and visibility.
How do you keep a search index in sync with the primary database?
Prefer change data capture: stream the database's change log (for example, with Debezium into Kafka) to an indexer, so every committed change is captured in order. Or use a transactional outbox. Avoid dual writes from app code, which drift when one side fails.
How do you change an index's mapping without downtime?
Create a new index with the new mapping, backfill it from the source of truth while also applying live changes, then atomically switch an alias from the old index to the new one, and delete the old index later.
Why is deep pagination expensive and what's the alternative?
To serve results 10,000-10,010, every shard must find and sort its top 10,010, and the coordinator merges all of them. Use cursor-style pagination (search_after with a sort key) or a point-in-time view instead of large offsets.