The Inverted Index

The data structure behind nearly every search engine. Why scanning text and the term-document incidence matrix do not scale, the dictionary and postings lists, building an index by sorting term-document pairs, dictionary data structures, and what postings can store.

An inverted index is the term-document incidence matrix with the zeros left out: a dictionary of terms with their document frequencies, and for each term a postings list of the documents containing it, sorted by docID. The matrix is sparse: on Reuters-21578 only 0.23 percent of the matrix's cells are 1s, so its 725,793 postings take 2.9 megabytes as 4-byte docIDs, against 39.4 megabytes for the bit matrix. Uncompressed postings are smaller whenever the density is below $1/32$. An index is built by sorting (term, docID) pairs and grouping them. A sorted dictionary of $M$ terms finds a term, or a missing term's place, in at most $\lfloor \log_2 M \rfloor + 1$ steps. DocIDs support Boolean queries, term frequencies ranking, and positions phrase queries.

In the architecture article, the thesis student's query arctic climate warming was answered from a table that listed, for each term, the documents containing it. This article explains why the table has that shape. The obvious alternative is to keep no index at all. Manning, Raghavan, and Schütze (2008, §1.1) open their textbook with such a case: a search for the plays of Shakespeare that contain Brutus and Caesar but not Calpurnia. With the complete works on one computer, a person could scan the text of every play, the way the Unix tool grep does. What structure answers such questions without reading the text again? A list, kept for each term, of the documents that contain it, built once by sorting.

Scanning works for a few megabytes. It fails for a billion documents, and it fails when thousands of queries arrive every second. It also gives no help with queries such as Romans within a few words of countrymen, or with ranking the results. The alternative is to process the collection once, in advance, into a structure that answers such questions directly. That structure is the inverted index. Zobel and Moffat (2006, §3) call it the most efficient index structure for text query evaluation, and almost every search engine uses one. The rest of this topic builds on it: the next two articles make it buildable at scale and small, and every retrieval model in the course reads its scores from it.

Here is the route. First we try the simplest possible index, the incidence matrix, and see it fail on size. Then we store only its 1s, which gives the inverted index. Next we build one by hand for the four Arctic sentences. Finally we decide how to store the dictionary and the postings, and what each posting should carry. Worked problems at the end build and query two more small indexes.

The term-document incidence matrix

The simplest index records, for every term and every document, whether the term occurs in the document. Arranged with terms as rows and documents as columns, this is the term-document incidence matrix. Here is part of the matrix for six of Shakespeare's plays (Manning, Raghavan, and Schütze, 2008, §1.1):

Antony and Cleopatra Julius Caesar The Tempest Hamlet Othello Macbeth
Antony 1 1 0 0 0 1
Brutus 1 1 0 1 0 0
Caesar 1 1 0 1 1 1
Calpurnia 0 1 0 0 0 0
Cleopatra 1 0 0 0 0 0
mercy 1 0 1 1 1 1
worser 1 0 1 1 1 0

Each row is a bit vector saying which documents contain a term. Each column is a bit vector saying which terms a document contains. A Boolean query becomes bitwise operations on rows, so the question about Brutus, Caesar, and Calpurnia can be answered without touching the text. The Boolean retrieval model works through that computation.

Where the matrix fails

The matrix fails on size. Consider a modest collection of $N = 1$ million documents, each about 1,000 words long, with a vocabulary of $M = 500{,}000$ distinct terms. The matrix has

$$M \times N = 500{,}000 \times 1{,}000{,}000 = 5 \times 10^{11}$$

cells, half a trillion. But the collection contains only about $10^{9}$ tokens in total. So at most $10^{9}$ cells can contain a 1, and fewer still, since repeated words in a document share a cell. The share of 1s is at most $10^{9} / (5 \times 10^{11}) = 0.2$ percent, so at least 99.8 percent of the matrix is zeros. The matrix is extremely sparse. Zipf's law describes how its 1s are spread: most terms are rare, so most rows are almost entirely empty. Storing the matrix explicitly spends nearly all of its space recording what is not there.

A real collection shows the same proportions. Take Reuters-21578 (Lewis, 1997), the 10,788 news stories from 1987 that this topic measures throughout. Lowercased and split into runs of letters, as in the term statistics article, it has 29,187 distinct terms. Its incidence matrix has $29{,}187 \times 10{,}788 = 314{,}869{,}356$ cells. Only 725,793 of them contain a 1, or 0.23 percent.

  • At one bit per cell, the matrix takes 39.4 megabytes.
  • Listing the 725,793 (term, document) pairs instead, as 4-byte document numbers, takes 2.9 megabytes, about a thirteenth as much.
  • The compression article shrinks that list to well under one megabyte.

More than half of the terms (59 percent) occur in only one or two stories. So more than half of the matrix's rows hold at most two 1s among 10,788 cells.

Example (a small matrix is not sparse). The incidence matrix of the thesis student's four Arctic sentences is not very sparse: about a third of its cells are filled. The sentences produce 16 index terms, so the matrix has $16 \times 4 = 64$ cells, and it has 22 ones, one for each distinct (term, document) pair, which is 34 percent. Sparsity comes with scale: each of ten thousand news stories uses a vanishing share of a large vocabulary.

The inverted index

The repair is to store only the 1s. For each term, record the list of documents that contain it. That is the inverted index. It is called inverted because it reverses the natural organization of a collection. A document lists the terms it contains; the index lists, for each term, the documents that contain it.

The index has two parts:

  • The dictionary, also called the vocabulary or lexicon, contains every term. For each term it stores the document frequency $\mathit{df}_t$, the number of documents containing the term, and a pointer to its postings list.
  • The postings lists, one per term, contain the identifiers of the documents in which the term occurs. Each entry is a posting. Together the lists form the postings file.

Each document is identified by a document identifier (docID), usually an integer assigned in the order documents are indexed. Postings lists are kept sorted by docID, and the sorting is what makes Boolean queries efficient. Two sorted lists can be intersected in a single pass, advancing through both at once. The pass takes time proportional to the lists' combined length. Intersecting postings lists develops that merge algorithm.

Building an index by sorting

How do the lists get built? The basic construction method has four steps (Manning, Raghavan, and Schütze, 2008, §1.2):

  1. Collect the documents to be indexed.
  2. Tokenize each document.
  3. Apply linguistic preprocessing (stop words, normalization, stemming) to produce index terms.
  4. Index the documents: produce a list of (term, docID) pairs, sort it, and group it into a dictionary and postings.

Back to the thesis student's four sentences from the architecture article:

docID Text
1 Arctic sea ice is declining as the climate warms.
2 A warming climate threatens Arctic seabirds and their food.
3 Climate models predict warmer winters in Europe.
4 Seabirds of the Arctic: a field guide.

The analysis is the one used there. Lowercase the text and keep runs of letters. Drop the eight stop words a, and, as, in, is, of, the, their. Stem the rest with the original Porter algorithm. The documents then produce these (term, docID) pairs, in document order:

(arctic,1) (sea,1) (ic,1) (declin,1) (climat,1) (warm,1)
(warm,2) (climat,2) (threaten,2) (arctic,2) (seabird,2) (food,2)
(climat,3) (model,3) (predict,3) (warmer,3) (winter,3) (europ,3)
(seabird,4) (arctic,4) (field,4) (guid,4)

The stems are not words: ice becomes ic and Europe becomes europ. That does no harm, as the Porter stemmer explains, because queries are stemmed by the same rules. Sorting the pairs by term, then by docID, brings all occurrences of each term together, in docID order:

(arctic,1) (arctic,2) (arctic,4) (climat,1) (climat,2) (climat,3)
(declin,1) (europ,3) (field,4) (food,2) (guid,4) (ic,1) (model,3)
(predict,3) (sea,1) (seabird,2) (seabird,4) (threaten,2) (warm,1)
(warm,2) (warmer,3) (winter,3)

Grouping consecutive pairs with the same term, and merging repeated pairs from the same document, gives the index:

Term $\mathit{df}$ Postings
arctic 3 1, 2, 4
climat 3 1, 2, 3
seabird 2 2, 4
warm 2 1, 2
declin, europ, field, food, guid, ic, model, predict, sea, threaten, warmer, winter 1 each one document each
The index of the four Arctic sentences drawn as a data structure. The dictionary on the left holds each term and its document frequency, sorted by term, and each entry points to a postings list of document numbers in increasing order. Notice how short most lists are: twelve of the sixteen terms have a single posting, and only arctic and climat reach three. In a real collection that spread covers several orders of magnitude.
The index of the four Arctic sentences drawn as a data structure. The dictionary on the left holds each term and its document frequency, sorted by term, and each entry points to a postings list of document numbers in increasing order. Notice how short most lists are: twelve of the sixteen terms have a single posting, and only arctic and climat reach three. In a real collection that spread covers several orders of magnitude.

The query seabird AND warm intersects the lists for seabird (2, 4) and warm (1, 2) and returns document 2.

Three things that are easy to miss

First, the document frequency in the dictionary is just the length of the postings list. It is stored separately because query processing and term weighting need it before reading the list, or instead of reading it.

Second, the sort does the real work. After it, grouping is a single pass that compares each pair with the one before it.

Third, the merging of repeated pairs is where information can be lost.

Example (a repeated word). If d1 had read "Arctic sea ice is declining as the sea warms", there would be 22 pairs and 21 postings, where the sort above handled 22 pairs and the index holds 22 postings. The new sentence trades climate for a second sea, so climat loses d1, and the pair (sea, 1) appears twice. Merging leaves one posting for it. A docID-only index then keeps no record that d1 mentions the sea twice. Keeping the count is the difference between the first two rows of the table in the section on postings.

Sorting is the expensive step. For a collection whose pairs fit in memory, it is a single in-memory sort. For one whose pairs do not, it must be done in blocks and merged, which is the subject of index construction.

Storing the dictionary

With the index built, how is a query term found in it? The dictionary is consulted for every query term, so it must support fast lookup. There are two main choices (Manning, Raghavan, and Schütze, 2008, §3.1):

  • A hash table maps each term directly to its entry, giving lookup in constant expected time. It cannot find terms by prefix, since similar terms hash to unrelated positions. It must also be rebuilt or resized as the vocabulary grows.
  • A search tree, usually a B-tree in disk-based systems, keeps terms in sorted order. Lookup takes logarithmic time. The tree supports prefix and range queries, such as all terms beginning with auto, which spelling correction and wildcard queries need. Wildcard Queries treats dictionary structures and pattern lookup in full.

Large systems often use a sorted array of terms, searched by binary search and stored compactly, as described in dictionary compression. In the example, the sixteen terms sorted are arctic, climat, declin, europ, field, food, guid, ic, model, predict, sea, seabird, threaten, warm, warmer, winter, at positions 0 to 15. Looking up the student's warm:

Step Range searched Middle position Term there Comparison
1 0 to 15 7 ic warm is later, so search 8 to 15
2 8 to 15 11 seabird warm is later, so search 12 to 15
3 12 to 15 13 warm found

Looking up ocean, which is not in the dictionary, takes one more step. After position 11 (seabird, later than ocean) the range is 8 to 10. Position 9 (predict) is also later, and position 8 (model) is earlier. The range is then empty, and the search ends with the information that ocean would sit between model and predict.

That last fact is what a hash table cannot provide. It is enough to find every term with a given prefix, since those terms are stored together, starting where the search ends. A search for the prefix sea lands at position 10 and reads forward through sea and seabird.

How many steps a lookup takes. A dictionary of $M$ terms needs at most $\lfloor \log_2 M \rfloor + 1$ steps, whether or not the term is present. The idea: every step that does not find the term discards at least half of the range.

Proof. Let the range searched hold $n$ positions, from $\mathit{lo}$ to $\mathit{hi}$, and let the middle position be $\mathit{mid} = \lfloor (\mathit{lo} + \mathit{hi})/2 \rfloor$. If the term at $\mathit{mid}$ is not the one sought, the search continues either to the left, in the $\mathit{mid} - \mathit{lo} = \lfloor (n-1)/2 \rfloor$ positions before $\mathit{mid}$, or to the right, in the $\mathit{hi} - \mathit{mid} = \lceil (n-1)/2 \rceil = \lfloor n/2 \rfloor$ positions after it. Either way at most $\lfloor n/2 \rfloor$ positions remain. Starting from $M$ positions, at most $\lfloor M/2^{j} \rfloor$ remain after $j$ unsuccessful steps. Step $j + 1$ can happen only if that number is at least 1, that is, if $2^{j} \le M$, or $j \le \lfloor \log_2 M \rfloor$. So there are at most $\lfloor \log_2 M \rfloor + 1$ steps. $\blacksquare$

The bound is 5 for these 16 terms, 15 for the 29,187 terms of Reuters-21578, and 19 for 400,000. The bound is attained for every $M$. A search for a term later than every term in the dictionary always continues to the right, where exactly $\lfloor n/2 \rfloor$ positions remain, so it makes exactly $\lfloor \log_2 M \rfloor + 1$ steps. Among the 16 terms, finding winter, the last, takes the five steps at positions 7, 11, 13, 14 and 15. The script checks that the worst case equals the bound for every dictionary size up to 2,000. The dictionary is much smaller than the postings, so it can usually be kept in memory even when the postings cannot.

Storing the postings

The other part of the index is the postings themselves. Postings lists vary enormously in length, from a single document for most terms to nearly every document for the most common ones. Two in-memory representations are common (Manning, Raghavan, and Schütze, 2008, §1.2):

  • linked lists, which make insertion cheap;
  • variable-length arrays, which use less space and are faster to scan because their contents are contiguous in memory.

In a simple static index on disk, each term's postings are stored as one contiguous run, so that a query reads each list sequentially. Indexes that are updated or compressed in blocks may split a list across several segments or blocks. Updating an Index works out what such segments cost to write and to query as documents arrive and are deleted.

What a posting carries

A posting can carry more than a docID, and what it carries determines what the system can do. The architecture article showed how each ranking model depends on particular statistics. In summary:

Posting contents Enables
docID only Boolean retrieval
docID and term frequency Weighted ranking such as TF-IDF and BM25
docID, term frequency, and positions Phrase and proximity queries, through a positional index
Any of the above, separated by field Searching or weighting titles, headings, or anchor text separately

What a posting stores need not be counted from the text. Learned Sparse Retrieval keeps this kind of index and lets a trained model set a weight for each posting, and even add postings for terms a document lacks.

In the Arctic example, the postings of climat and warm look like this in each form. Positions are counted over all the words of a document, including the removed stop words, so that the original word distances are kept. In d1, for instance, climate is the eighth word and warms the ninth.

Term docIDs docID: tf docID: positions
climat 1, 2, 3 1:1, 2:1, 3:1 1:⟨8⟩, 2:⟨3⟩, 3:⟨1⟩
warm 1, 2 1:1, 2:1 1:⟨9⟩, 2:⟨2⟩

Example (two documents, one phrase). Both d1 and d2 contain climat and warm, but only d2 contains the phrase warming climate. The phrase becomes warm followed by climat, so the position of climat must be one more than that of warm. In d2 they are at 2 and 3. In d1 they are at 9 and 8: d1 says climate warms, the same two terms in the other order. The docID lists alone answer warm AND climat with both documents and cannot tell them apart. The positional index article develops the merge that checks positions.

Each richer form costs space. On Reuters-21578 the docID-only index has 725,793 postings. A positional index must also store a position for each of the collection's 1,330,267 tokens, before any stop words are removed.

Collection-level statistics live elsewhere. The dictionary stores each term's document frequency, and a separate table stores each document's length and any document-level scores. Many systems also keep a forward index, mapping each document to its terms, or a copy of the document text. These serve for generating snippets and for computing features that depend on the whole document.

Why the inverted index won

Was the inverted index the only candidate? No. Other structures have been proposed for text search:

  • Signature files store a compact bit pattern for each document. After a careful comparison, Zobel, Moffat, and Ramamohanarao (1998) concluded that inverted files were faster, smaller, and more flexible than signature files for the text-indexing workloads they studied.
  • Suffix arrays (Manber and Myers, 1993) index every position in the text. They support arbitrary substring search. The array holds one entry for every character position of the text, where an inverted index holds one for every (term, document) pair, and it has to be rebuilt or patched when the text changes.

The inverted index is space-efficient because it stores only what occurs. It is query-efficient because a query reads only the postings of its own terms. And it extends naturally to everything retrieval needs: frequencies, positions, fields, and compression.

Worked problems

The first three problems are Exercises 1.1 to 1.3 of the course text (Manning, Raghavan, and Schütze, 2008, §1.2), restated here with their data. The last two are posed on this article's own examples. In the three exercises the documents are indexed as given: every word is a term, with no stop list and no stemming. Every result is checked in tools/experiments/indexing/toy_index.py.

Problem 1 (Exercise 1.1: build an index). Build the inverted index for these four documents.

docID Text
1 new home sales top forecasts
2 home sales rise in july
3 increase in home sales in july
4 july new home sales rise

Solution. We follow the construction of this article: list the (term, docID) pairs, sort them, and group them. The documents have 5, 5, 6 and 5 words, so there are 21 pairs. Sorted by term and then by docID they are

(forecasts,1) (home,1) (home,2) (home,3) (home,4) (in,2) (in,3) (in,3)
(increase,3) (july,2) (july,3) (july,4) (new,1) (new,4) (rise,2) (rise,4)
(sales,1) (sales,2) (sales,3) (sales,4) (top,1)

The pair (in, 3) occurs twice, because document 3 uses in twice. Merging it leaves 20 postings under 9 terms:

Term $\mathit{df}$ Postings
forecasts 1 1
home 4 1, 2, 3, 4
in 2 2, 3
increase 1 3
july 3 2, 3, 4
new 2 1, 4
rise 2 2, 4
sales 4 1, 2, 3, 4
top 1 1

The document frequencies add up to the number of postings: $1 + 4 + 2 + 1 + 3 + 2 + 2 + 4 + 1 = 20$.

Problem 2 (Exercise 1.2: matrix and index). For the four documents below, draw (a) the term-document incidence matrix and (b) the inverted index.

docID Text
1 breakthrough drug for schizophrenia
2 new schizophrenia drug
3 new approach for treatment of schizophrenia
4 new hopes for schizophrenia patients

Solution. (a) The collection has ten distinct terms. Each row of the matrix has a 1 in the column of every document that contains the term:

Term d1 d2 d3 d4
approach 0 0 1 0
breakthrough 1 0 0 0
drug 1 1 0 0
for 1 0 1 1
hopes 0 0 0 1
new 0 1 1 1
of 0 0 1 0
patients 0 0 0 1
schizophrenia 1 1 1 1
treatment 0 0 1 0

The column sums are the documents' lengths, 4, 3, 6 and 5, since no document repeats a word. The matrix has $10 \times 4 = 40$ cells and $4 + 3 + 6 + 5 = 18$ ones, a density of 45 percent.

(b) The inverted index stores, for each row, the columns that hold a 1:

Term $\mathit{df}$ Postings
approach 1 3
breakthrough 1 1
drug 2 1, 2
for 3 1, 3, 4
hopes 1 4
new 3 2, 3, 4
of 1 3
patients 1 4
schizophrenia 4 1, 2, 3, 4
treatment 1 3

It has 18 postings, one for each 1 of the matrix.

Problem 3 (Exercise 1.3: two Boolean queries). For the collection of Problem 2, find the documents returned by (a) schizophrenia AND drug and (b) for AND NOT (drug OR approach).

Solution. A document matches x AND y if it is on both postings lists, x OR y if it is on at least one of them, and NOT x if it is not on the list of x.

(a) The list of schizophrenia is 1, 2, 3, 4 and the list of drug is 1, 2. The documents on both are 1 and 2. The query returns documents 1 and 2.

(b) The list of drug is 1, 2 and the list of approach is 3, so drug OR approach matches documents 1, 2 and 3. The list of for is 1, 3, 4. Removing from it the documents that match drug OR approach leaves document 4 alone. The query returns document 4, new hopes for schizophrenia patients. The same answers can be read from the matrix of Problem 2: in (a) the rows of the two terms are 1111 and 1100, and both hold a 1 in columns 1 and 2. The Boolean retrieval model treats these operations in general.

Problem 4 (when the matrix is the smaller structure). An incidence matrix stores one bit per cell, and an uncompressed postings file stores each posting as a 32-bit docID. Find the density of 1s below which the postings file is smaller, and apply the result to Reuters-21578, to the four Arctic sentences, and to the million-document collection of this article.

Solution. Let the matrix have $M$ terms and $N$ documents, and let $P$ be the number of 1s, which is also the number of postings. The matrix takes $MN$ bits and the postings take $32P$ bits. The postings are smaller exactly when $32P < MN$, that is, when the density $P/(MN)$ is below $1/32 = 3.125$ percent.

  • Reuters-21578 has $P = 725{,}793$ and $MN = 314{,}869{,}356$, a density of 0.23 percent, far below the threshold. The matrix takes $314{,}869{,}356 / 8$ bytes, or 39.4 megabytes, and the postings $725{,}793 \times 4$ bytes, or 2.9 megabytes. The ratio is 13.6, which is the "about a thirteenth" of the section on the matrix.
  • The Arctic sentences have $P = 22$ and $MN = 64$, a density of 34.4 percent, above the threshold. Their matrix takes 64 bits, or 8 bytes, and their postings $22 \times 4 = 88$ bytes. For a collection this small the matrix is the smaller structure.
  • The million-document collection has at most $10^{9}$ ones in $5 \times 10^{11}$ cells, a density of at most 0.2 percent. The matrix takes $5 \times 10^{11} / 8$ bytes, or 62.5 gigabytes. The postings take at most $10^{9} \times 4$ bytes, or 4 gigabytes.

Problem 5 (binary search in the dictionary). In the sorted dictionary of the sixteen Arctic terms, trace the lookups of field and of zebra, which is not a term. Compare the number of steps with the bound proved above.

Solution. The terms sit at positions 0 to 15 in the order arctic, climat, declin, europ, field, food, guid, ic, model, predict, sea, seabird, threaten, warm, warmer, winter. The middle of a range from $\mathit{lo}$ to $\mathit{hi}$ is position $\lfloor (\mathit{lo} + \mathit{hi})/2 \rfloor$.

For field:

Step Range searched Middle position Term there Comparison
1 0 to 15 7 ic field is earlier, so search 0 to 6
2 0 to 6 3 europ field is later, so search 4 to 6
3 4 to 6 5 food field is earlier, so search 4 to 4
4 4 to 4 4 field found

For zebra:

Step Range searched Middle position Term there Comparison
1 0 to 15 7 ic zebra is later, so search 8 to 15
2 8 to 15 11 seabird zebra is later, so search 12 to 15
3 12 to 15 13 warm zebra is later, so search 14 to 15
4 14 to 15 14 warmer zebra is later, so search 15 to 15
5 15 to 15 15 winter zebra is later, and the range is empty

The first lookup takes 4 steps and the second 5. The bound is $\lfloor \log_2 16 \rfloor + 1 = 5$, so the lookup of zebra reaches it. The search ends with the information that zebra would be stored after winter, the last term.

What we have learned

An inverted index is the incidence matrix with the zeros left out: a dictionary of terms with their document frequencies, and a sorted postings list for each. Building one means producing (term, docID) pairs, sorting them, and grouping them, as we did for the Arctic sentences. A sorted dictionary supports binary search and prefix lookup. What each posting carries fixes which queries the system can answer: only positions told d2's warming climate apart from d1's climate warms.

For four sentences, the sort took no time at all. Reuters-21578 already produces 725,793 pairs, and the collections that search engines index produce billions, far more than fit in memory. The next article, Index Construction, establishes how such a collection is sorted and grouped: in blocks that fit in memory, written to disk and merged.

References

  • Lewis, D. D. (1997). Reuters-21578 text categorization test collection, distribution 1.0. record · 11 pages
  • Manber, U., and Myers, G. (1993). Suffix arrays: A new method for on-line string searches. SIAM Journal on Computing, 22(5), 935–948. record
  • Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, sections 1.1–1.2 and 3.1. Cambridge University Press. record · 102 pages
  • Zobel, J., and Moffat, A. (2006). Inverted files for text search engines. ACM Computing Surveys, 38(2), article 6. record · 2 pages
  • Zobel, J., Moffat, A., and Ramamohanarao, K. (1998). Inverted files versus signature files for text indexing. ACM Transactions on Database Systems, 23(4), 453–490. record

Reviewed: verified, 16 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 11 revisions