Highlights

Contents

Part III
03

The inverted index

We reverse the document-to-words relationship. Repeating scans wastes work that an ordered list can avoid. We will build posting lists, intersect them, compress them, and maintain their changes.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Search basics: why LIKEfails2Tokenization and analysis3The inverted index4Ranking: TF-IDF and BM255The indexing pipeline6Shards and replicas7Autocomplete and fuzzysearch8Operating a searchcluster9Case study: search end toend

#Section 9Build the term dictionary

Take the four reports introduced earlier. Instead of asking each report whether it contains red, prepare the answer once. An inverted index maps a term to the documents containing it. A term dictionary supplies the lookup structure for the distinct terms.

Walking the corpus emits twelve token occurrences. The dictionary contains red, bird, scores, blue, match, and live. For red, the document IDs are 1 and 3. For bird, they are 1, 2, and 4. The engine can now start a query for red bird from two narrow lists rather than from every body string.

REVERSE THE RELATIONSHIPdocuments hold wordsterms point to doc@positiondoc 1red bird scoresdoc 2blue bird scoresdoc 3red match livedoc 4bird bird matchinvertred1@13@1bird1@22@24@14@2scores1@32@3blue2@1match3@24@3live3@3birdbirdbirdbird12 occurrences, 6 distinct termsdoc 4 keeps both birds
Figure 15.9Computed postings and positions for the illustrative four-document corpus. Repeated terms keep their occurrences.

A posting is an entry linking a term to a document, often carrying frequency or positions. The posting list collects those entries for a term in a useful order. Document identifiers are commonly sorted because sorted lists support efficient merging and compact differences. The exact storage format depends on the engine and codec.

The dictionary need not load every term into a giant hash table. Ordered dictionaries and compact prefix structures can support term lookup and prefix enumeration. The essential inversion is logical. Its physical representation should match query frequency, storage size, and access patterns.

#Section 10Intersect lists without scanning bodies

The query requires both red and bird. The sorted lists are [1,3] and [1,2,4]. Start pointers at their first entries. Both are 1, so emit document 1 and advance both. Now compare 3 with 2. Advance the smaller value to 4. Compare 3 with 4 and advance the smaller list until it ends. The intersection is [1].

Intersection retains IDs present in every required list. A two-pointer merge examines list entries in increasing order, giving a bound proportional to the lengths of both lists. Starting with the rarest term can reduce later candidate checks. Skip data and block bounds let optimized engines avoid examining every occurrence.

POINTERS ADVANCE TOWARD AGREEMENTred13bird124result11red 1 = bird 1emit 1, advance both2red 3 > bird 2advance bird3red 3 < bird 4advance red: list endstwo pointers, one passadvance the smaller ID
Figure 15.10Computed intersection trace for the tiny corpus. The final candidate is document 1.

Exhausting either required list ends an intersection immediately because no later common ID can exist. Empty posting lists therefore give a cheap negative result. A deleted or unauthorized candidate can still disappear after the intersection, so a nonempty term intersection does not guarantee a visible answer. Keep those later predicates in the trace when explaining why a query returns nothing.

For an any-term query, union retains IDs present in at least one list. Here the union is [1,2,3,4]. These distinct semantics affect both candidate count and ranking. A common word can produce a long list even in an inverted index, so explain selectivity before promising constant-time search.

#Section 11Frequency and compression change storage

Document 4 contains bird twice. Storing only membership loses that fact, while storing positions implicitly retains it. Term frequency counts a term’s occurrences within a document. It is useful for scoring, but raw repetition should not dominate without limit.

A sorted document list [1,2,4] can store gaps [1,1,2]. Delta encoding stores differences between adjacent increasing values. Small differences often take fewer bytes with a variable-length integer representation. Blocks can also store packed integers and skip metadata. Compression decreases bytes read but adds decoding work.

STORE DIFFERENCES, RECOVER IDS012345+1doc 1+1doc 2+2doc 4gaps stored112running sum11+1=22+2=4recovers 1, 2, 4sorted IDs leavesmall numbers
Figure 15.11Computed delta-encoding trace. Byte savings depend on a chosen codec, so no unmeasured compression ratio is claimed.

In a deliberately simple uncompressed occurrence representation, twelve IDs at four bytes each occupy 48 bytes, and twelve four-byte positions occupy another 48 bytes. That does not include terms, headers, document values, source text, or dictionaries. It is a bookkeeping example, not a model of a production index’s footprint. Count the information stored before estimating a compression ratio.

#Section 12Updates create a new representation

A report changes from red bird scores to red match live. The old document ID still appears in the bird list unless the index represents deletion or replacement. A common segment-based design treats existing segments as immutable, marks an old document version dead, and adds the replacement in new data.

A segment is a separately searchable chunk of an index. Immutable segments permit readers to use a stable view while writers build new data. A live-document mask records which stored document versions still count as visible. Queries apply that mask so obsolete postings do not become results.

OLD POSTINGS CAN REMAIN PHYSICALLYsegment 1, immutabled1 red bird scoresd2 blue bird scores01live masksegment 2, newerd1 red match live1birdquery viewreturns d2 onlymerge latersegment 3, after a merged2 blue bird scoresd1 red match livethe dead entry is reclaimed here
Figure 15.12Illustrative update mechanism. Logical deletion and physical reclamation occur at different times.

A merge rewrites selected segments into fewer segments, discarding dead entries when safe. This can reduce query overhead and reclaim storage, but consumes CPU and I/O. Write throughput must account for this background work. A system that handles a short ingestion burst may still fail during sustained merge pressure.