Unit 6 · Index Compression¶
1. Setting the scene¶
Scenario: The index is bigger than the budget
The overnight SPIMI build now finishes. But operations reports: the postings file for CityDocs is several gigabytes, the dictionary alone does not leave room for caching, and every query hits the disk. The proposal on the table is to buy a larger server.
You suspect a cheaper answer: store the same index in far fewer bytes, without making search slower.
Guiding questions
- How large will the vocabulary become as the archive keeps growing?
- Why do some postings lists have millions of entries and others only one?
- Can decompressing data ever be faster than reading it uncompressed?
2. Intended learning outcomes¶
| # | Outcome | Bloom | CLO |
|---|---|---|---|
| ILO 6.1 | Explain how compression reduces disk, memory and transfer costs of an inverted index. | UNDERSTAND | 4 |
| ILO 6.2 | Estimate vocabulary size with Heaps' law and fit its parameters from two observations. | ANALYSE | 4 |
| ILO 6.3 | Relate Zipf's law to the distribution of postings list lengths. | UNDERSTAND | 4 |
| ILO 6.4 | Calculate dictionary size under fixed width, string, blocking and front coding schemes. | APPLY | 4 |
| ILO 6.5 | Encode and decode postings with gap, Variable Byte and γ (gamma) codes. | APPLY | 4 |
3. Why compress?¶
flowchart LR
DK[("Disk<br/>compressed index")] -->|"read 250 MB<br/>instead of 1,000 MB"| RAM["Memory"] -->|"fast decompression<br/>small CPU cost"| QP["Query processing"]
- Less disk space: saves money.
- More of the index fits in memory, which means faster queries (caching).
- Less data transferred from disk to memory.
Premise: decompression algorithms are fast. Under that premise, reading compressed data and decompressing it is often faster than reading uncompressed data.
An inverted index has two parts, and we compress them for different reasons:
| Part | Content | Why compress |
|---|---|---|
| Dictionary | terms + df + pointer to postings | keep it entirely in memory: every query starts with a lookup |
| Postings | docIDs (and frequencies, positions) | it is the largest part; less to read per query |
All techniques in this unit are lossless. (Case folding, stemming and stopword removal can be seen as lossy compression: they discard distinctions for good.)
4. Term statistics: what preprocessing does to the index¶
RCV1, sizes in thousands (K):
| Step | Dictionary (types) | Δ% | cumul. | Nonpositional postings | Δ% | cumul. | Positional postings | Δ% | cumul. |
|---|---|---|---|---|---|---|---|---|---|
| Unfiltered | 484 | 109,971 | 197,879 | ||||||
| No numbers | 474 | −2 | −2 | 100,680 | −8 | −8 | 179,158 | −9 | −9 |
| Case folding | 392 | −17 | −19 | 96,969 | −3 | −12 | 179,158 | 0 | −9 |
| 30 stopwords | 391 | 0 | −19 | 83,390 | −14 | −24 | 121,858 | −31 | −38 |
| 150 stopwords | 391 | 0 | −19 | 67,002 | −30 | −39 | 94,517 | −47 | −52 |
| Stemming | 322 | −17 | −33 | 63,812 | −4 | −42 | 94,517 | 0 | −52 |
Explain the zeros
- Case folding → 0 % positional:
Apple,apple,APPLEmerge into one type, but every occurrence (position) is still stored. Types shrink; positions do not. - Stemming → 0 % positional:
connect, connected, connection→connect; three positions before, three after. - Stopwords → 0 % dictionary: removing 30 or 150 words removes at most 150 entries out of ~390,000 types (invisible in the dictionary), yet those few words account for a huge share of postings, because they occur everywhere.
5. How big does the vocabulary get? Heaps' law¶
Is there a maximum vocabulary size, doesn't English have a fixed number of words? No. Real collections keep producing new terms: names (designDorf, Potsdam), typos and variants, numbers and product codes (iphone17, berlin2026), technical terms, hashtags, other languages, emojis.
Heaps' law
$$ M = k\,T^{\,b} $$ \(M\) = vocabulary size (distinct terms), \(T\) = number of tokens, typically \(30 \le k \le 100\) and \(b \approx 0.5\).
The vocabulary keeps growing, but more slowly than the collection.
| Tokens \(T\) | \(M = 10\,T^{0.5}\) | \(\log_{10} T\) | \(\log_{10} M\) |
|---|---|---|---|
| 100 | 100 | 2 | 2.0 |
| 1,000 | 316 | 3 | 2.5 |
| 10,000 | 1,000 | 4 | 3.0 |
| 100,000 | 3,162 | 5 | 3.5 |
| 1,000,000 | 10,000 | 6 | 4.0 |
xychart-beta
title "Heaps' law M = 10 T^0.5 on a log log plot"
x-axis "log10 T (tokens)" [2, 3, 4, 5, 6]
y-axis "log10 M (distinct terms)" 0 --> 5
line [2.0, 2.5, 3.0, 3.5, 4.0]
Why use a log log plot?¶
Taking logarithms turns the power law into a straight line, because \(\log(a^b) = b\log a\):
In the table, every +1 in \(\log T\) gives +0.5 in \(\log M\): a constant slope \(b = 0.5\). The slope tells how fast new words appear (\(b \approx 0.4\) slow, \(0.5\) square root growth, \(0.7\) fast).
Worked example: RCV1
\(T = N \times L = 800{,}000 \times 200 = 1.6 \times 10^8\) tokens; observed \(M = 400{,}000\).
The published least squares fit is \(\log_{10} M = 0.49 \log_{10} T + 1.64\), i.e. \(k = 10^{1.64} \approx 44\), \(b = 0.49\):
The model overestimates by ~57,000 terms (~14 %): Heaps' law is an estimate, not a count.
Spelling errors and Heaps' law¶
Including typos (informtion, informatoin, infromation) makes every error a new term: \(M\uparrow\) and effectively a larger \(k\)/\(b\). Automatic correction maps them back and compresses the vocabulary.
6. How often does each term occur? Zipf's law¶
Zipf's law
$$ \mathit{cf}_i = \frac{K}{i} \qquad\Longrightarrow\qquad \log \mathit{cf}_i = \log K - \log i $$ The \(i\)th most frequent term occurs about \(1/i\) as often as the most frequent one (a line with slope −1 on a log log plot).
| Rank \(i\) | Example term | Predicted \(\mathit{cf}_i\) for \(K = 10^6\) |
|---|---|---|
| 1 | the | 1,000,000 |
| 2 | of | 500,000 |
| 3 | and | 333,333 |
| 10 | system | 100,000 |
| 100 | retrieval | 10,000 |
| 1,000 | compression | 1,000 |
flowchart LR
F["Frequent terms<br/>the · of · and"] --> FL["Very long postings<br/>1, 2, 3, 4, 5, …"]
M["Medium terms<br/>retrieval"] --> ML["Medium postings<br/>17, 44, 98, 203, …"]
R["Rare terms<br/>arachnocentric"] --> RL["Short postings<br/>519002"]
xychart-beta
title "Zipf's law with K = 10^6 on a log log plot"
x-axis "log10 rank i" [0, 0.3, 0.48, 1, 2, 3]
y-axis "log10 cf" 0 --> 7
line [6, 5.7, 5.52, 5, 4, 3]
Heaps explains why the dictionary grows; Zipf explains why postings are extremely uneven. So a good code must be short for small numbers and only as long as necessary for large ones.
7. Dictionary compression¶
Search starts with a dictionary lookup, so the dictionary should live in memory.
Attempt 1: fixed width entries¶
\(400{,}000 \times 28 = 11.2\) MB. Wasteful: a still occupies 20 bytes: and restrictive: hydrochlorofluorocarbons does not fit.
Attempt 2: dictionary as a string¶
Store all terms in one long string; each entry keeps a 3 byte pointer to where its term starts (the next pointer marks its end).
Per term: 4 (df) + 4 (postings ptr) + 3 (term ptr) + ~8 (characters) = 19 bytes → \(400{,}000 \times 19 \approx 7.6\) MB.
Attempt 3: blocking¶
Store a term pointer only for every \(k\)th term, and prefix each term with a 1 byte length.
Per block of 4: without blocking \(4 \times 3 = 12\) bytes of pointers; with blocking \(3 + 4 \times 1 = 7\) bytes → 5 bytes saved per block.
Worked example
\(400{,}000 / 4 = 100{,}000\) blocks × 5 bytes = 500,000 bytes ≈ 0.5 MB → 7.6 → 7.1 MB.
The trade off: binary search now finds the block, then scans linearly inside it. Larger \(k\) → less space, slower lookup.
Attempt 4: front coding¶
Consecutive sorted terms share prefixes. Store the prefix once:
| Representation | Size |
|---|---|
| Fixed width entries | 11.2 MB |
| Dictionary as a string | 7.6 MB |
| + blocking (\(k = 4\)) | 7.1 MB |
| + blocking + front coding | 5.9 MB |
A 47 % reduction without losing a single term.
8. Postings compression¶
RCV1 has \(10^8\) postings. With 4 byte integers that is 400 MB. A docID among 800,000 documents needs only \(\lceil\log_2 800{,}000\rceil = 20\) bits: but even 20 bits is too much for the postings of the.
Step 1: store gaps, not docIDs¶
Postings are sorted, so store the difference to the previous docID:
| docIDs | 33 | 47 | 154 | 159 | 202 |
|---|---|---|---|---|---|
| gaps | 33 | 14 | 107 | 5 | 43 |
For frequent terms the gaps are tiny (the → 1, 1, 1, 1, …); for rare terms they are large. The original list is recovered by a running sum.
Step 2: variable length codes¶
A gap of 5 = 101₂ needs 3 bits, not 32. Variable length encoding gives small gaps short codes and large gaps longer ones.
Variable Byte (VB) encoding¶
Each byte = 1 continuation bit + 7 payload bits. Split the number into 7 bit groups; the last byte has continuation bit 1, earlier bytes 0.
| docID | 824 | 829 | 215406 |
|---|---|---|---|
| gap | 824 | 5 | 214577 |
| VB code | 00000110 10111000 |
10000101 |
00001101 00001100 10110001 |
Worked example: encode 824
\(824 = 1100111000_2\) → 7 bit groups from the right: 0000110 | 0111000 → add continuation bits: 0+0000110, 1+0111000 → 00000110 10111000.
Decode: read 00000110 (c=0, continue), 10111000 (c=1, stop) → payloads 0000110 0111000 → \(6 \times 128 + 56 = 824\).
γ (gamma) codes¶
Work at the bit level. Write \(G\) in binary and drop the leading 1 → offset. Encode the offset's length in unary (n ones followed by a zero). γ = length ∥ offset.
| \(G\) | binary | offset | length (unary) | γ code |
|---|---|---|---|---|
| 1 | 1 | none | 0 | 0 |
| 2 | 10 | 0 | 10 | 10 0 |
| 3 | 11 | 1 | 10 | 10 1 |
| 4 | 100 | 00 | 110 | 110 00 |
| 9 | 1001 | 001 | 1110 | 1110 001 |
| 13 | 1101 | 101 | 1110 | 1110 101 |
| 24 | 11000 | 1000 | 11110 | 11110 1000 |
(Spaces are for readability only: γ codes are prefix free, so no separators are stored.)
Length of \(\gamma(G)\): \(2\lfloor \log_2 G \rfloor + 1\) bits: e.g. \(\gamma(13)\) has \(2 \cdot 3 + 1 = 7\) bits.
def vb_encode_number(n: int) -> list[int]:
out = []
while True:
out.insert(0, n % 128)
if n < 128:
break
n //= 128
out[-1] += 128 # set continuation bit on the last byte
return out
def vb_decode(stream: list[int]) -> list[int]:
numbers, n = [], 0
for byte in stream:
if byte < 128:
n = 128 * n + byte
else:
numbers.append(128 * n + byte - 128)
n = 0
return numbers
def gamma(g: int) -> str:
offset = bin(g)[3:] # drop '0b' and the leading 1
return "1" * len(offset) + "0" + offset
def gaps(doc_ids): return [d - p for d, p in zip(doc_ids, [0] + doc_ids[:-1])]
ids = [824, 829, 215406]
code = [b for g in gaps(ids) for b in vb_encode_number(g)]
print([f"{b:08b}" for b in code])
print(vb_decode(code), gamma(13))
Variable Byte vs. γ¶
| Feature | Variable Byte | γ code |
|---|---|---|
| Unit | bytes | bits |
| Implementation | simple | more complex |
| Speed | usually faster (byte aligned) | slower (bit manipulation) |
| Compression | good | often better for small gaps |
| Parameters | none | none (parameter free, prefix free) |
Other unit sizes exist: nibbles (4 bits), 32/64 bit words (e.g. Simple-9, PForDelta), trading compactness for CPU friendliness. VB is popular in practice because it balances simplicity, speed and compression.
9. Classwork: estimate a web vocabulary¶
Heaps' law from two observations (20 min)
A web collection has \(M_1 = 3{,}000\) terms after \(T_1 = 10{,}000\) tokens and \(M_2 = 30{,}000\) terms after \(T_2 = 1{,}000{,}000\) tokens. A search engine indexes \(2 \times 10^{10}\) pages of 200 tokens. Estimate the vocabulary size.
Solution
- Tokens: \(T = 2\times10^{10} \times 200 = 4\times10^{12}\).
- Exponent: divide the two equations so \(k\) cancels: \(\dfrac{M_2}{M_1} = \left(\dfrac{T_2}{T_1}\right)^b \Rightarrow 10 = 100^b \Rightarrow b = 0.5\).
- Constant: \(3{,}000 = k \cdot 10{,}000^{0.5} = 100k \Rightarrow k = 30\).
- Prediction: \(M = 30 \times (4\times10^{12})^{0.5} = 30 \times 2\times10^{6} = 6\times10^{7}\) → about 60 million terms.
Even with short pages, a web scale collection yields a huge dictionary: the motivation for dictionary compression.
10. Check your understanding¶
Encode the postings [3, 7, 11, 23, 29] as gaps and then as γ codes.
Gaps: 3, 4, 4, 12, 6 → γ: 101, 11000, 11000, 1110100, 11010 (concatenated: 1011100011000111010011010).
Why does gap encoding alone not save space?
If each gap is still stored in a fixed 32 bit integer, small numbers take as many bits as large ones. Gaps only pay off combined with a variable length code.
What does blocking trade, and how do you choose k?
Memory for lookup speed: larger \(k\) saves more pointer bytes but increases the linear scan inside a block. Choose the largest \(k\) whose lookup cost remains acceptable (small values like 4 to 8 are typical).
11. Key takeaways¶
- Compression saves money and time: more index in RAM, fewer bytes to read.
- Heaps' law \(M = kT^b\): vocabulary grows without bound, but sublinearly; fit it on a log log plot.
- Zipf's law \(\mathit{cf}_i \propto 1/i\): a few terms have huge postings, most are rare.
- Dictionary: fixed width → string → blocking → front coding (11.2 → 5.9 MB on RCV1).
- Postings: gaps + variable length codes (VB for speed, γ for compactness).
12. Link to assessment¶
In the project README, report your collection statistics (documents, tokens, vocabulary, postings) and, optionally, fit Heaps' law to your own data. Teams using the big data stack should discuss storage size and any compression (e.g. Parquet, VB encoded postings).
Further reading¶
- Manning, Raghavan & Schütze, Introduction to IR, ch. 5.
- Witten, Moffat & Bell, Managing Gigabytes, 2nd ed.