SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Inverted Index
  • Trie (Prefix Tree)
  • LRU Cache Design
  • Heap and Priority Queue
  • Bitmaps and Roaring Bitmaps
  • Ring Buffer
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Data Structures for Scale

Inverted Index

The word-to-documents list behind every search box: how it is built, stored, compressed and queried.

โฑ 13 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

An inverted index flips the usual picture. Instead of "document โ†’ words", it stores "word โ†’ list of documents that contain it". To answer a search, you read the lists of the query words and combine them. You never open the documents.

  • Term: one word (after cleaning). Postings list: the sorted doc IDs for that term.
  • AND = intersect two sorted lists. OR = merge them. Both use two pointers and one pass.
  • Lists are compressed (store gaps, not full IDs) and written in segments that are merged later.

02Concept: What is it?

The page "Full-Text Search Engines" explains how text is cleaned and ranked. This page is about the data structure under it: how the lists are laid out, combined, squeezed and spread over machines.

A normal (forward) index is like a book's pages: page 5 contains these words. An inverted index is like the index at the back of the book: the word "apple" appears on pages 3, 17 and 42. Looking up a word is fast because the dictionary of terms is sorted (or hashed), and each term points straight to its list.

A posting is usually more than a doc ID. It can carry the term frequency (how often the word appears, used for ranking) and the positions of each occurrence (used for phrase queries such as "red apple", where the words must sit next to each other).

Two parts: the dictionary and the postings
๐Ÿ“–Dictionaryapple, banana, green, pie, red ...
โ†’โ†“pointer
๐Ÿ“‹Postings for โ€œappleโ€doc 1, 2, 3, 5 (+ freq, positions)
The dictionary is small and kept in memory. The postings are large and read from disk only for the words you ask for.
๐Ÿง Sorted lists are the secret
If every list is sorted by doc ID, then AND and OR need only one pass with two pointers. No hash table, no nested loops. Everything else on this page is built on that one choice.

03Real-Life Example

๐ŸตThe Back-of-the-Book Index
You want every page that mentions both "apple" and "red". You do not read the book. You open the index, find "apple: 1, 2, 3, 5" and "red: 1, 3, 5". You run a finger down both lists. Pages 1, 3 and 5 appear in both. Done, in a few steps, in a book of any size.
Book index
Inverted index
A word in the index
A term
The list of page numbers
The postings list (doc IDs)
Page numbers in order
Doc IDs sorted
Two fingers down two lists
Two-pointer intersection
Bold page numbers for main mentions
Term frequency or field weight
โ€œsee alsoโ€ ranges like 12-15
Compressed gaps and runs
A new edition adds an appendix index
A new segment, merged later
Documents flipped into an index
๐Ÿ“„doc 1: red apple pie
โ†’โ†“split into words
๐Ÿ”คred, apple, pie
โ†’โ†“add id to each list
๐Ÿ“‹apple: [1]red: [1] pie: [1]
Each document is read once. Each word then gets its own list.

04Why Do We Need It?

โšกFast lookups
Cost depends on the length of the query wordsโ€™ lists, not on the size of the whole collection.
๐ŸงฉCheap combining
AND, OR and NOT are single passes over sorted lists.
๐ŸชถCompact
Gaps between sorted IDs are small numbers, so postings compress to a fraction of their size.
๐Ÿ“ˆScales out
Split the index into shards and search them in parallel.
๐Ÿ†Ranking-friendly
Frequencies and positions sit next to the IDs, so scoring needs no second lookup.
๐Ÿ”Easy to update
Write small new segments, and merge them in the background.
An inverted index turns "search every document" into "read a few sorted lists", and that is the reason search boxes feel instant on billions of pages.

05Where Do We Use It?

๐Ÿ”ŽSearch engines
Web search, site search and product search all sit on postings lists.
๐ŸงฐElasticsearch, OpenSearch, Solr
All three use Lucene segments, which are inverted indexes.
๐Ÿ—„๏ธDatabase full-text search
PostgreSQL GIN indexes and MySQL full-text indexes are inverted indexes.
๐Ÿ“œLog search
Finding every log line with โ€œtimeoutโ€ across terabytes.
๐Ÿท๏ธTags and filters
โ€œAll products with tag redโ€ is a postings list per tag.
๐Ÿ“งEmail and chat search
Per-user indexes of words to messages.

06Types / Parts / How It Works

What goes into a posting

Index levelEach posting holdsWhat it allowsCost
Doc IDs onlydoc IDYes/no matching, AND / OR / NOTSmallest
+ term frequencydoc ID, countRanking by TF-IDF or BM25A little more
+ positionsdoc ID, count, positionsPhrase and nearby-word queriesLargest, often 2 to 3 times more
+ payloadsextra bytes per postingField weights, boosts, offsets for highlightingVaries

Combining lists

QueryHow the lists are combinedCost
A AND BIntersect: advance the smaller pointer, keep equal IDsAbout the size of the lists, less with skips
A OR BMerge: output the smaller, keep equal IDs onceSum of the list sizes
A AND NOT BWalk A, drop IDs that also appear in BSum of the list sizes
Phrase โ€œA Bโ€Intersect, then check positions differ by 1Intersect plus position checks
Many ANDsStart with the shortest list, then intersect the rest into itMuch smaller than the order written

Making lists small and quick

Delta encoding and variable-byte numbers
๐Ÿ”ขDoc IDs1000, 1004, 1010, 1011
โ†’โ†“store gaps
โž–Gaps1000, 4, 6, 1
โ†’โ†“varint
๐Ÿ“ฆBytes2 bytes, 1, 1, 1
Store the gap from the previous ID. Small gaps fit in one byte.
  • Skip pointers: every so many entries, store a pointer that lets an AND jump ahead over IDs that cannot match.
  • Block compression: pack 128 gaps at a time with a fixed bit width (for example, Frame of Reference). It is fast to decode.
  • Bitmaps: for very common terms, a bitmap per term can beat a list (see Bitmaps and Roaring Bitmaps).

Spreading the index over machines

Two ways to shard
By document (common)
๐Ÿ—‚๏ธShard 1: docs 1 to 1Mhas its own full index
๐Ÿ—‚๏ธShard 2: docs 1M to 2Mhas its own full index
By term (rare)
๐Ÿ”คShard 1: terms a to mall docs for those words
๐Ÿ”คShard 2: terms n to zall docs for those words
Most search engines split by document. Every shard answers every query.
Scatter to all shards, then merge top results Hot terms overload one shard
VisualizerIntersect and merge sorted postings listsPick a query, then press Next. Watch the two pointers move one step at a time, and compare the number of comparisons with scanning every document.
Query
The 6 documents
  • 1 red apple pie
  • 2 green apple tree
  • 3 apple juice red
  • 4 banana pie
  • 5 red banana apple
  • 6 green tree house
The inverted index (term โ†’ sorted doc ids)
  • apple: [1, 2, 3, 5]
  • banana: [4, 5]
  • green: [2, 6]
  • house: [6]
  • juice: [3]
  • pie: [1, 4]
  • red: [1, 3, 5]
  • tree: [2, 6]
red
135
apple
1235
result
(empty)
Comparisons so far: 0. Amber = just compared. Cyan = pointer now. Grey = already passed.
Step 1 of 6
Step 1: red AND apple (shortest list first)
Put one pointer at the start of each sorted list.
Matching docs
1, 3, 5
the answer
Comparisons
4
two-pointer merge
Entries in used lists
7
at most this many read
Full scan
6 docs
read every document
Answer: doc 1 (โ€œred apple pieโ€), doc 3 (โ€œapple juice redโ€), doc 5 (โ€œred banana appleโ€). The index only touched the lists of the query words. A scan must open every document, and the gap grows with the collection: at a million documents a rare word may have only a few hundred entries.

With only 6 documents the saving is small, so look at the shape instead: the work depends on the list lengths, not on the number of documents. Real engines also use skip pointers to jump over long runs.

07How to Use It / Steps / Implementation

Building and using the index

  1. 1
    Clean the text
    Split into words, lowercase, remove noise. The same steps must run on the query.
  2. 2
    Collect (term, doc ID) pairs
    One pair for every word in every document.
  3. 3
    Sort and group
    Sort by term, then by doc ID. Each term now has its sorted list.
  4. 4
    Write the dictionary and postings
    Keep the dictionary in memory, with a pointer to each list on disk.
  5. 5
    Compress the lists
    Gaps first, then variable-byte or block packing.
  6. 6
    Answer queries with two pointers
    Start with the shortest list for AND queries, and use skip pointers to jump.
  7. 7
    Add new data as new segments
    Never edit a segment. Merge small ones into bigger ones in the background.
Intersect two sorted lists (pseudocode)
function intersect(a, b):
  i = 0; j = 0; out = []
  while i < a.length and j < b.length:
    if a[i] == b[j]: out.push(a[i]); i++; j++
    else if a[i] < b[j]: i++
    else: j++
  return out
๐Ÿ’กDeletes and updates
Segments are never edited. A delete is a small marker (a deleted-docs bitmap). A merge later drops those documents for good. An update is a delete plus a new add.

08Key Terms to Know

TermMeaning in easy words
Inverted indexA map from each term to the documents that contain it
TermOne cleaned word that is stored in the dictionary
Dictionary (lexicon)The sorted list of all terms, with pointers to their postings
Postings listThe sorted doc IDs for one term
PostingOne entry: doc ID plus maybe frequency and positions
Term frequency (TF)How many times a term appears in a document
Document frequency (DF)How many documents contain the term. Also the length of the list
Skip pointerA shortcut in a list that lets an intersection jump ahead
Delta (gap) encodingStoring the difference from the previous ID instead of the ID
SegmentAn immutable piece of the index. New data makes new segments
MergeCombining segments into a bigger one and dropping deleted documents
Forward indexThe opposite direction: document to its words

09Pros, Cons and Trade-offs

โœ… Pros
  • Query cost depends on the words, not on the collection size
  • AND, OR and NOT are a single pass
  • Compresses to a small fraction of the text
  • Frequencies and positions allow ranking and phrases
  • Immutable segments are simple, safe and cache-friendly
โš ๏ธ Cons
  • Heavy to build and rebuild
  • Updates are not in place: new segments and merges
  • Position data can make it larger than the text
  • Hot terms make long lists and slow queries
  • Needs the same text cleaning at index and at query time

Trade-offs

ChoiceWe gainWe lose
Store positionsPhrase queriesIndex size and write cost
Heavy compressionLess disk and memoryMore CPU to decode
Skip pointersFaster AND on long listsA little extra space
Few big segmentsFaster queriesMore merge work
Shard by documentEasy balance and writesEvery query hits every shard
Shard by termFewer machines per queryHot terms, hard rebalancing

10Common Problems and Mistakes

Common mistakes

  1. Unsorted postings. The two-pointer trick fails silently and results are wrong.
  2. Different cleaning at query time. The query word "Running" never meets the stored word "run".
  3. ANDing in the written order. Start with the shortest list and the work drops a lot.
  4. Indexing stop words and giant fields. It wastes space and creates the longest lists.
  5. Too many tiny segments. Every query must check each one, so latency rises until merges catch up.
  6. Sharding by term for a skewed vocabulary. A few common words overload a few machines.
  7. Treating the index as the source of truth. It is derived data, so keep the original and be able to rebuild.

Things to watch

๐Ÿ˜Very long lists
A word in nearly every document gives a huge list. Treat it as a stop word, or use a bitmap.
โฑ๏ธRefresh delay
New documents appear only after the next segment is opened, often about a second.
๐ŸงฎDeep paging
Page 10,000 of results needs every shard to return that many hits.
๐Ÿ’พMerge storms
Large merges use disk and CPU, and can slow searches.

11Real-World Examples

๐ŸชถApache Lucene
The library under Elasticsearch, OpenSearch and Solr. Immutable segments, block-compressed postings and skip data.
๐Ÿ˜Elasticsearch
Splits an index into shards by document and sends each query to all of them, then merges the top results.
๐Ÿ˜PostgreSQL GIN
A generalised inverted index for full-text, arrays and JSON.
๐Ÿ”Google web search
Famous for index shards by document, replicated widely, with ranked results merged at the top.
๐Ÿ“ŠClickHouse and Druid
Use bitmap-style inverted indexes to filter by tags and dimensions fast.
๐Ÿ“œLog tools
Loki, Splunk and others keep an index of terms or labels pointing at chunks of logs.
Mini case: one search over three shards
๐Ÿ”ŽQueryred AND apple
โ†’โ†“sent to all shards
๐Ÿ—‚๏ธ3 shardseach intersects its lists
โ†’โ†“top 10 each
๐ŸCoordinatormerges to a global top 10
Each shard searches its own documents. The coordinator merges the top hits.

12Related Topics to Read Next

Full-Text Search Enginesโ†’

The cleaning and ranking built on top of this structure.

Indexingโ†’

Database indexes compared with inverted indexes.

Bitmaps and Roaring Bitmapsโ†’

A faster way to store the longest postings lists.

Shardingโ†’

How an index is split across machines.

Bloom Filtersโ†’

Another cheap way to say โ€œnot in this segmentโ€.

MapReduceโ†’

The classic way to build huge inverted indexes.

Trie (Prefix Tree)โ†’

The usual structure for the term dictionary and autocomplete.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Idea: term โ†’ sorted list of doc IDs.
  • โœ”AND: two-pointer intersection, shortest list first.
  • โœ”OR: two-pointer merge, equal IDs once.
  • โœ”Extras per posting: frequency for ranking, positions for phrases.
  • โœ”Compress: delta gaps plus varint or block packing, and skip pointers.
  • โœ”Updates: immutable segments, background merges, deletes as markers.
  • โœ”Shard: by document, ask every shard, merge the top results.
  • โœ”One line: โ€œFlip the data: ask the word where it lives, not the page what it says.โ€
โ† Previous
Exactly-Once Processing
Next โ†’
Trie (Prefix Tree)