Inverted index

On this page 7

An inverted index is a data structure that maps each term to a list of the documents in which it appears, together with optional positions and frequencies. It is the backbone of lexical search engines and, in the retrieval & knowledge layer of modern artificial intelligence systems, it powers sparse retrieval for BM25 ranking, hybrid search and many retrieval-augmented generation (RAG) pipelines.

The name reflects a reversal of the natural layout: a document collection lists the words each document contains, while an inverted index lists the documents each word points to. This inversion lets a query touch only the few lists that match its terms instead of scanning the entire corpus.

How an inverted index is structured

An inverted index has two main parts. The dictionary, also called the vocabulary or term lexicon, stores every distinct term with a pointer to its data. The postings lists store, for each term, the sorted identifiers of matching documents, usually with the term frequency and, in positional indexes, the word offsets inside each document.

The following table describes the information that a typical postings entry can carry and what each field enables at query time.

FieldExample valueWhat it enables
Document ID4127Boolean matching and set operations
Term frequency3TF-IDF and BM25 scoring
Positions12, 48, 97Phrase and proximity queries
Payload or fieldtitleField boosting and filtering
Document lengthStored separatelyLength normalization in BM25
Contents of a postings entry

The dictionary itself is held in a compact structure such as a sorted array, B-tree or finite-state transducer, which supports fast exact lookup and prefix or fuzzy expansion. Collection statistics, including the number of documents containing each term, are kept alongside it because they feed inverse document frequency.

Building and updating the index

Index construction starts with text analysis: tokenization, lowercasing, optional stemming or lemmatization and stop-word handling. The analyzer must be identical at indexing and query time, otherwise a query for “running” will not match documents indexed under the stem “run”.

Large collections are indexed with sort-based or single-pass in-memory construction: the indexer builds partial indexes in memory, writes them to disk as immutable segments and later merges them. Engines such as Apache Lucene, which underlies Elasticsearch and OpenSearch, follow this segment-and-merge design, so new documents become searchable after a refresh without rewriting existing data.

Deletions are usually recorded in a tombstone bitmap and removed physically only during merges, and an update is implemented as a delete plus a new insert. The table below compares the main maintenance strategies.

StrategyHow it worksTrade-off
Full rebuildReindex the whole corpus periodicallySimple but slow and costly
Immutable segmentsAdd new segments, merge in backgroundFast writes, extra merge I/O
In-place updateModify postings directlyComplex locking, rare in practice
Logical deletionMark documents deleted until mergeCheap deletes, temporary waste
Index maintenance strategies

Query processing and compression

To answer a query, the engine looks up each query term in the dictionary and intersects or unions the postings lists. Conjunctive queries walk the lists in parallel, using skip pointers to jump over long runs of nonmatching documents; disjunctive ranked queries accumulate scores per document.

For top-k retrieval, dynamic pruning algorithms such as WAND and Block-Max WAND skip documents whose maximum possible score cannot enter the current top results. They often reduce the number of scored documents by an order of magnitude while returning exactly the same top-k list.

Postings are stored as gaps between sorted document IDs rather than raw IDs, because small numbers compress well. The table lists common encodings.

SchemePrincipleTypical use
Variable-byte7 data bits per byte with a continuation flagSimple, decent decode speed
PForDeltaFixed bit width per block plus exceptionsFast SIMD-friendly decoding
Elias-FanoSplits values into high and low bitsCompact with fast random access
Roaring bitmapsMixed arrays, bitmaps and runsDense lists and filters
Common postings compression schemes

With such schemes, a compressed index commonly occupies roughly 10 to 30 percent of the raw text size, depending on whether positions are stored.

Inverted index compared with vector indexes

In retrieval for AI applications, the inverted index serves exact lexical matching, whereas vector indexes such as HNSW or an IVF index serve approximate nearest neighbor search over dense embeddings. The two structures answer different questions and are frequently combined.

AspectInverted indexVector index
RepresentationSparse term weightsDense embedding vectors
MatchingExact terms after analysisSemantic similarity
StrengthsNames, codes, rare keywordsParaphrases and synonyms
ResultsExact for the scoring modelApproximate recall
ExplainabilityMatched terms are visibleSimilarity is opaque
Inverted index versus dense vector index

Learned sparse retrieval models such as SPLADE produce expanded term weights that are stored in an ordinary inverted index, combining neural relevance with lexical infrastructure. In hybrid search, results from BM25 over an inverted index and from a vector index are merged, often with reciprocal rank fusion, before reranking.

Limitations and common mistakes

The main limitation is the vocabulary mismatch problem: a query about “car” does not match a document that only says “automobile” unless synonyms, query expansion or learned sparse weights bridge the gap.

  • Mismatched analyzers between indexing and querying silently lower recall.
  • Aggressive stop-word removal breaks phrase queries such as “to be or not to be”.
  • Poor tokenization of code, product numbers or languages without spaces, such as Chinese or Japanese, requires dedicated analyzers or n-gram indexing.
  • Too many small segments slow queries until merges run; refresh and merge policies need tuning.

Despite these issues, an inverted index remains the most efficient structure for keyword retrieval at scale, and it is a strong baseline that dense retrieval systems should be measured against.

Understanding it simply

An inverted index works like the index at the back of a book. You look up a word. The index tells you every page where that word appears. You do not need to read the whole book.

A search engine builds the same kind of list for millions of documents. When you type a few words, it checks only the lists for those words. Then it ranks the documents that match. This is why keyword search feels instant, even across a huge collection.

Applied in practice

A software company builds a RAG assistant over 400,000 support tickets and manuals. Pure vector search answers general questions well but often misses tickets that mention exact error codes such as “ERR-5021”, because the embedding model treats the code as noise.

The team adds an inverted index with BM25 scoring alongside the vector index, using a custom analyzer that keeps error codes and version numbers as single tokens. Both retrievers return 50 candidates, which are merged with reciprocal rank fusion and passed to a cross-encoder reranker. On an internal test set of 600 questions, recall at 10 rises noticeably for code-specific queries, while index size grows by only a few gigabytes and query latency stays well under 100 milliseconds.