Storing each sorted postings list as the gaps between its docIDs, and encoding the gaps with variable-length codes, shrinks the postings without loss to about a quarter of their size. On the 725,793 postings of Reuters-21578, 2.903 MB of 32-bit integers become 0.868 MB with variable byte codes (9.57 bits per posting), 0.783 MB with Elias gamma codes (8.63) and 0.733 MB with delta codes (8.08), against a pooled gap entropy of 7.19 bits. A gamma code's expected length is at most $2H + 1$ bits whenever smaller gaps are at least as probable as larger ones, but not for every distribution. Gamma wins on frequent terms and loses on rare ones; byte-aligned codes usually decode faster.
Index construction moved every posting of Reuters-21578 to disk and back, and on Reuters there are 725,793 of them. Stored as 32-bit integers, they take 2.9 megabytes. The postings of the Reuters RCV1 collection contain about 100 million document identifiers, which occupy 400 megabytes. Every merge, every query, and every byte of memory spent on the index pays for that size. How much smaller can an index be made without losing anything, and does making it smaller cost search speed?
The answers are encouraging. Encoded with the two simple codes described in this article, RCV1's postings occupy about 116 megabytes with variable byte codes and about 101 megabytes with Elias gamma codes, roughly a quarter of the original size (Manning, Raghavan, and Schütze, 2008, §5.3, Table 5.6). The dictionary can be reduced from 11.2 megabytes to about 5.9, as Dictionary Compression shows. None of this loses any information.
Compression matters for speed as well as space. A compressed index lets more of the postings stay in memory, and the parts that must be read from disk transfer faster. Decompressing simple codes is quick, so reading compressed postings and decoding them is usually faster than reading uncompressed postings.
Here is the route, following Manning, Raghavan, and Schütze (2008, ch. 5). First we separate lossless compression from the lossy kind text processing already applied. The dictionary was shrunk in the previous article, so we turn to the postings: storing gaps instead of docIDs, then two codes for the gaps, variable byte and Elias gamma, each worked bit by bit on two real Reuters lists. We prove how far a gamma code can be from the best possible code, derive the textbook's estimate of the compressed index size from Zipf's law, and work delta and Rice codes on the same lists. We measure every code on the whole collection. Finally we ask what decoding costs, look at the codes current systems use, and see how renumbering documents makes gaps smaller.
Lossless and lossy
The compression in this article is lossless: the original index can be reconstructed exactly. Several earlier steps in text processing are, in effect, lossy compression. Stop-word removal, case folding, and stemming each discard distinctions to make the index smaller, and the discarded information cannot be recovered. Static index pruning goes further, removing postings that are unlikely to affect the top results of any query (Carmel et al., 2001). Lossy methods change what the index can answer, while lossless methods only change how it is stored.
The smaller structure of the index, the dictionary, is compressed by changing its layout: the terms are stored as one string, in blocks, with shared prefixes written once. That takes the RCV1 dictionary from 11.2 megabytes to about 5.9, and the 29,187 terms of Reuters-21578 from 817.2 kilobytes to 422.5. Dictionary Compression works each step. The rest of this article is about the postings.
Compressing the postings: gaps
The dictionary was the small part. The postings are where the bytes are. A postings list is a sorted sequence of docIDs, and docIDs in a large collection are large numbers.
The key observation is that a sorted list can be stored as the differences between consecutive entries. These are called gaps, or d-gaps, and the original list is recovered by adding them up. The Arctic index's list for arctic, documents 1, 2, and 4, becomes the gaps 1, 1, 2. Manning, Raghavan, and Schütze (2008, §5.3, Table 5.3) give three larger lists:
| Term | docIDs | Gaps |
|---|---|---|
| the | 283042, 283043, 283044, 283045 | 283042, 1, 1, 1 |
| computer | 283047, 283154, 283159, 283202 | 283047, 107, 5, 43 |
| arachnocentric | 252000, 500100 | 252000, 248100 |
Frequent terms, which have the longest lists, have the smallest gaps, often 1. Rare terms have large gaps, but their lists are short. This is the distribution described by Zipf's law, and it is what makes postings compressible: most of the numbers stored in an index are small. A variable-length code, which uses few bits for small numbers and more bits for large ones, exploits it.
Two real lists
Two lists from Reuters-21578 (Lewis, 1997) carry through the rest of this article. The stories are numbered 1 to 10,788 in order of their Reuters identifiers, which is roughly the order they were filed. Palladium, a rare term, occurs in five stories. Oil occurs in 1,038, and its first ten postings are shown:
| Term | docIDs | Gaps |
|---|---|---|
| palladium | 1467, 1521, 1792, 1795, 8079 | 1467, 54, 271, 3, 6284 |
| oil (first ten) | 3, 39, 80, 91, 94, 95, 101, 119, 121, 126 | 3, 36, 41, 11, 3, 1, 6, 18, 2, 5 |
The gaps of palladium are mostly large, since five postings are spread over ten thousand stories, though two of them, 3 and 54, are small. The gaps of oil are small, with an average of 10.4 over the whole list (rounded to one decimal), because a story mentioning oil appears every few stories. Across the whole collection:
- 15 percent of all gaps are exactly 1;
- 80 percent are below 128;
- none can reach 16,384, since there are only 10,788 stories.
Those last two thresholds are not arbitrary. They are where the first code below moves from one byte to two, and from two to three.
Variable byte codes
Variable byte (VB) encoding uses a whole number of bytes for each gap. The low 7 bits of each byte carry data. The high bit, the continuation bit, marks the last byte of a number. In the convention of Manning, Raghavan, and Schütze, it is set to 1 on the last byte and 0 on the others. Many implementations use the opposite convention, setting the bit to 1 when more bytes follow. Either works, as long as the encoder and decoder agree. To encode a gap, write it in binary, pad it on the left with zeros to a multiple of 7 bits, cut it into 7-bit groups, and put a continuation bit in front of each group:
| Gap | Binary | 7-bit groups | VB encoding |
|---|---|---|---|
| 1 | 1 |
0000001 |
10000001 |
| 5 | 101 |
0000101 |
10000101 |
| 130 | 10000010 |
0000001 0000010 |
00000001 10000010 |
| 824 | 1100111000 |
0000110 0111000 |
00000110 10111000 |
| 214577 | 110100011000110001 |
0001101 0001100 0110001 |
00001101 00001100 10110001 |
For 824, the binary representation 1100111000 has ten digits. Padded to fourteen, it splits into the 7-bit groups 0000110 and 0111000. The first byte carries 0000110 with continuation bit 0, and the last carries 0111000 with continuation bit 1. For 214577, the eighteen binary digits are padded to twenty-one and give three groups. The first two bytes have continuation bit 0 and the third has 1. A decoder reads bytes, accumulating 7 bits at a time, until it reads a byte whose high bit is 1.
The length follows from the construction. A gap $G$ has $\lfloor \log_2 G \rfloor + 1$ binary digits and each byte carries 7 of them, so the code takes
$$8 \left\lceil \frac{\lfloor \log_2 G \rfloor + 1}{7} \right\rceil$$
bits. Gaps below $2^7 = 128$ take one byte, and gaps below $2^{14} = 16{,}384$ take two.
VB codes are simple and fast to decode, because they work on whole bytes. They reduce RCV1's postings from 400 to about 116 megabytes.
Example (three-byte gaps). A gap of 16,384 needs three bytes, and no Reuters-21578 gap needs that many. 16,384 is $2^{14}$, which takes 15 binary digits, one more than two 7-bit groups can hold. The formula agrees: $8 \lceil 15/7 \rceil = 24$ bits. No Reuters gap reaches that size, because no gap can exceed the 10,788 stories. Every Reuters gap takes one byte or two.
Variable byte on a real list
Back to palladium. Encoding its gaps one at a time:
| Gap | Binary | 7-bit groups | VB bytes |
|---|---|---|---|
| 1467 | 10110111011 |
0001011 0111011 |
00001011 10111011 |
| 54 | 110110 |
0110110 |
10110110 |
| 271 | 100001111 |
0000010 0001111 |
00000010 10001111 |
| 3 | 11 |
0000011 |
10000011 |
| 6284 | 1100010001100 |
0110001 0001100 |
00110001 10001100 |
The 7-bit groups are taken from the right, so the leftmost group is padded with zeros. Each group then receives its continuation bit: 0 on every byte but the last of a number, 1 on the last. The five gaps take 8 bytes, 64 bits, against 160 bits as 32-bit integers. The stored stream is
00001011 10111011 10110110 00000010 10001111 10000011 00110001 10001100
Decoding needs no separators.
- Start with $n = 0$. The first byte,
00001011, has high bit 0, so it is not the last: $n = 128 \times 0 + 11 = 11$. - The second,
10111011, has high bit 1, so it ends the number. Its low 7 bits are 59, and $n = 128 \times 11 + 59 = 1467$. - Reset $n$ to 0 and continue.
10110110ends at once, giving 54, and so on.
Adding the gaps back up, $1467$, $1467 + 54 = 1521$, $1521 + 271 = 1792$, and so on, recovers the docIDs.
For the first ten postings of oil, every gap is below 128, so each takes exactly one byte, 80 bits in all. One byte per gap is also the floor for VB: a gap of 1 costs as much as a gap of 127.
Elias gamma codes
That floor is the weakness. Byte alignment wastes space on small gaps: a gap of 1, the most common value in many lists, still takes eight bits. Bit-level codes can do better. The Elias gamma code (Elias, 1975) represents a positive integer $G$ in two parts:
- the offset: $G$ in binary with the leading 1 removed, since every positive integer's binary form begins with 1;
- the length: the number of bits in the offset, written in unary, as that many 1s followed by a 0.
The code is the length followed by the offset. For 13, binary 1101, the offset is 101, three bits long, so the length is 1110, and the code is 1110101:
| Gap | Length | Offset | Gamma code | Bits |
|---|---|---|---|---|
| 1 | 0 |
0 |
1 | |
| 2 | 10 |
0 |
100 |
3 |
| 5 | 110 |
01 |
11001 |
5 |
| 9 | 1110 |
001 |
1110001 |
7 |
| 13 | 1110 |
101 |
1110101 |
7 |
| 24 | 11110 |
1000 |
111101000 |
9 |
| 511 | 111111110 |
11111111 |
11111111011111111 |
17 |
| 1025 | 11111111110 |
0000000001 |
111111111100000000001 |
21 |
How long is a gamma code? Here is the idea in one sentence: the unary length spends one bit for every bit of the offset, so the code takes about twice the bits of $G$ itself.
The formal version. $G$ has $\lfloor \log_2 G \rfloor + 1$ binary digits, so its offset has $\lfloor \log_2 G \rfloor$. The unary length spends one 1 for each offset bit plus a closing 0, which is $\lfloor \log_2 G \rfloor + 1$ bits. Adding the two parts gives
$$2\lfloor \log_2 G \rfloor + 1$$
bits, about twice the minimum needed to write $G$ in binary. For 13, $\lfloor \log_2 13 \rfloor = 3$, and the code has $2 \times 3 + 1 = 7$ bits, as in the table.
The code is prefix-free, meaning no code is the beginning of another. A sequence of codes can therefore be decoded without separators: read 1s until a 0 to learn the length, then read that many bits of offset.
Proof that the code is prefix-free. Suppose the code of $G$ is a prefix of the code of $G'$. Let $k$ be the number of offset bits of $G$. The code of $G$ begins with $k$ ones and then a 0, so the code of $G'$ begins the same way: its first 0 is also in position $k + 1$. The position of the first 0 is the unary length, so $G'$ has $k$ offset bits too. Both codes then have $2k + 1$ bits, and a string that is a prefix of another string of the same length is equal to it. Equal codes have equal offsets, and restoring the leading 1 gives $G = G'$. So no code is a proper prefix of another. $\blacksquare$
The code is also parameter-free: its definition mentions no property of the collection, so nothing has to be measured or tuned before encoding, and an index that grows never needs re-encoding because a parameter has gone stale. Gamma codes reduce RCV1's postings to about 101 megabytes, smaller than VB.
Example (the gamma code of 6). The gamma code of 6 is 11010, 5 bits. 6 is binary 110, so the offset is 10, two bits long, and the length is 110. The formula agrees: $2 \lfloor \log_2 6 \rfloor + 1 = 2 \times 2 + 1 = 5$. The gap of 6 in oil's list, below, takes exactly that.
Gamma on the same lists
For the rare term palladium:
| Gap | Length (unary) | Offset | Bits |
|---|---|---|---|
| 1467 | 11111111110 |
0110111011 |
21 |
| 54 | 111110 |
10110 |
11 |
| 271 | 111111110 |
00001111 |
17 |
| 3 | 10 |
1 |
3 |
| 6284 | 1111111111110 |
100010001100 |
25 |
The list takes 77 bits, more than the 64 of variable byte. Large gaps are where gamma is weak. Its unary length grows one bit for every doubling of the gap. So it spends about $2\log_2 G$ bits where VB spends about $\frac{8}{7}\log_2 G$, rounded up to whole bytes. The two exact lengths, $2\lfloor \log_2 G \rfloor + 1$ and $8\lceil (\lfloor \log_2 G \rfloor + 1)/7 \rceil$, divide the gaps into four ranges:
| Gap $G$ | Gamma bits | VB bits | Shorter code |
|---|---|---|---|
| 1 to 15 | 1 to 7 | 8 | gamma |
| 16 to 127 | 9 to 13 | 8 | VB |
| 128 to 255 | 15 | 16 | gamma |
| 256 and above | 17 or more | 16 or more | VB |
The two lengths are never equal, since one is odd and the other even. The last row holds for every larger gap. Write $k = \lfloor \log_2 G \rfloor \ge 8$. For $k = 8$ the lengths are 17 and 16. For $k \ge 9$, VB takes at most $8(k + 7)/7$ bits, and $2k + 1 > 8(k+7)/7$ is the same as $14k + 7 > 8k + 56$, that is $6k > 49$, which holds from $k = 9$ on. The script checks all four rows for every gap up to $2^{22}$. For the first ten postings of oil the comparison reverses:
| Gap | Gamma code | Bits | VB bits |
|---|---|---|---|
| 3 | 101 |
3 | 8 |
| 36 | 11111000100 |
11 | 8 |
| 41 | 11111001001 |
11 | 8 |
| 11 | 1110011 |
7 | 8 |
| 3 | 101 |
3 | 8 |
| 1 | 0 |
1 | 8 |
| 6 | 11010 |
5 | 8 |
| 18 | 111100010 |
9 | 8 |
| 2 | 100 |
3 | 8 |
| 5 | 11001 |
5 | 8 |
Gamma needs 58 bits for these ten gaps, against 80 for VB. Over the whole list of 1,038 postings it needs 5,728 bits, 5.5 bits per posting, against VB's 8.
Decoding the stream 10111111000100... shows that the codes need no separators. Read 1s up to the first 0: there is one 1, so the offset has one bit. Read that bit (1) and restore the leading 1 to get binary 11, which is 3. Then 111110 announces a five-bit offset, 00100, giving binary 100100, which is 36.
How far a gamma code is from the best possible code
A gamma code spends about twice the bits of $G$ itself. Whether that is a good price depends on which gaps occur how often. Here is the idea. A code can be short for some integers only by being long for others, so the best code for a collection depends on the probabilities of its gaps. A gamma code is fixed in advance and is not the best code for most collections. But whenever smaller gaps are at least as probable as larger ones, and the entropy defined below is above one bit, it is within a factor of 3 of the best code, whatever the probabilities are.
Against writing $G$ in binary. The course text takes $\log_2 G$ bits as its benchmark: if the $2^n$ gaps from 1 to $2^n$ were equally likely, a fixed-length code would need $n$ bits for each. The gamma length satisfies $2\lfloor \log_2 G \rfloor + 1 \le 2\log_2 G + 1$, so a gamma code is at most one bit longer than twice that benchmark (Manning, Raghavan, and Schütze, 2008, §5.3.2). Gaps are not equally likely, though, so the right benchmark is the entropy.
The lower bound (cited). Let $P$ be a probability distribution on the positive integers, with $P(G)$ the probability of the gap $G$. Its entropy is
$$H(P) = -\sum_{G} P(G) \log_2 P(G),$$
measured in bits, where terms with $P(G) = 0$ are left out. A code that gives the gap $G$ a codeword of $\ell(G)$ bits has expected length $E[\ell] = \sum_G P(G)\,\ell(G)$. Shannon's source coding theorem says that every prefix-free binary code has $E[\ell] \ge H(P)$, and the same bound holds for every code that can be decoded unambiguously (Cover and Thomas, 2006, §§5.3 and 5.5). No code averages fewer bits per gap than the entropy. Perplexity and Source Coding proves the bound, for every uniquely decodable code, and accounts for the bits each code of this article spends above it.
The upper bound (proved here). Write $\ell_\gamma(G) = 2\lfloor \log_2 G \rfloor + 1$ for the gamma length.
Theorem. Let $P$ be a distribution on the positive integers with $P(1) \ge P(2) \ge P(3) \ge \cdots$ and finite entropy. Then
$$E[\ell_\gamma] \le 2H(P) + 1.$$
Proof. Fix a gap $G$. The $G$ integers $1, 2, \ldots, G$ each have probability at least $P(G)$, because the probabilities do not increase, and their probabilities sum to at most 1. So $G \cdot P(G) \le 1$, that is, $G \le 1/P(G)$ whenever $P(G) > 0$. Taking logarithms, $\log_2 G \le \log_2 (1/P(G))$. Then
$$\ell_\gamma(G) = 2\lfloor \log_2 G \rfloor + 1 \le 2\log_2 G + 1 \le 2\log_2 \frac{1}{P(G)} + 1.$$
Multiply by $P(G)$ and sum over all gaps with $P(G) > 0$:
$$E[\ell_\gamma] = \sum_G P(G)\,\ell_\gamma(G) \le 2\sum_G P(G) \log_2 \frac{1}{P(G)} + \sum_G P(G) = 2H(P) + 1. \qquad \blacksquare$$
Dividing by $H(P)$ and using the lower bound gives the result in the form the course text states it. For a distribution with $1 < H(P) < \infty$,
$$1 \le \frac{E[\ell_\gamma]}{H(P)} \le 2 + \frac{1}{H(P)} \le 3,$$
so gamma encoding is within a factor of 3 of the optimal code, and the factor approaches 2 as the entropy grows (Manning, Raghavan, and Schütze, 2008, §5.3.2). A code with a guarantee of this kind, within a constant factor of optimal for every distribution of a class, is called universal. The term is from the paper that introduced the gamma code, "Universal codeword sets and representations of the integers" (Elias, 1975). The property there is that assigning messages in order of decreasing probability to codewords in order of increasing length gives an average length below a constant times the optimal one, for any source with positive entropy. For integers that are coded by their own codewords, that ordering is the hypothesis of the theorem above.
Example (a common misstatement). "Gamma codes are within a factor of 3 of optimal for any distribution of gaps" is false as it stands. Take the distribution that gives probability $1/4$ to each of the four gaps $2^{20}, 2^{20}+1, 2^{20}+2, 2^{20}+3$. Its entropy is $\log_2 4 = 2$ bits, and a two-bit code is optimal. The gamma code spends $2 \times 20 + 1 = 41$ bits on each of the four, a ratio of 20.5. The course text states the bound without proof and adds that it "holds for any probability distribution" (§5.3.2), and it defines a universal code in the same generality, for an arbitrary distribution. This distribution has entropy above one bit and breaks the bound, so the statement fails in that generality. Elias's property is not affected, because it lets the most probable message take the shortest codeword. A code for gaps cannot reorder its codewords: the gap $G$ must receive the codeword of the integer $G$. What the theorem above proves is the bound $E[\ell_\gamma] \le 2H(P) + 1$ under the hypothesis that probabilities do not increase with the size of the gap. The example violates that hypothesis: the gap $2^{20}$ has probability $1/4$ and every smaller gap has probability 0.
The gamma code wastes nothing. For each $k \ge 0$ there are $2^k$ integers with $\lfloor \log_2 G \rfloor = k$, each with a code of $2k + 1$ bits. So
$$\sum_{G \ge 1} 2^{-\ell_\gamma(G)} = \sum_{k \ge 0} 2^k \cdot 2^{-(2k+1)} = \sum_{k \ge 0} 2^{-(k+1)} = 1.$$
Every infinite binary string begins with exactly one gamma code or consists only of 1s. If its first 0 is at position $k + 1$, the string begins with the gamma code whose offset is its next $k$ bits, and with no other, since the code is prefix-free. The sum equal to 1 says the same thing by weight: no bit pattern is left unused. The sum also identifies the one distribution for which gamma is exactly optimal, $P(G) = 2^{-\ell_\gamma(G)}$, which is between $1/(2G^2)$ and $2/G^2$. For that distribution $\ell_\gamma(G) = \log_2(1/P(G))$ for every $G$, so $E[\ell_\gamma] = H(P)$.
On Reuters-21578. Pool the 725,793 gaps of all the postings lists into one distribution. It has 8,911 distinct values and an entropy of 7.19 bits. So no single prefix-free code that gives each gap value one codeword can average fewer than 7.19 bits per posting on this index. The gamma code averages 8.63 bits, a ratio of 1.20, far inside the bound $2H + 1 = 15.37$. The measured distribution is not exactly nonincreasing, since counts of neighboring large gaps fluctuate. But the proof used only the inequality $G \cdot P(G) \le 1$, and here the largest value of $G \cdot P(G)$ is 0.308. The bound says nothing about codes that change from list to list, such as the Rice codes below, which can go under the pooled entropy by fitting a parameter to each list.
The index size predicted from Zipf's law
How large will a gamma-coded index be? The course text derives an estimate from Zipf's law alone, before any index is built (Manning, Raghavan, and Schütze, 2008, §5.3.2). Here is the plan of the derivation. Zipf's law gives the frequency of the term of each rank. The frequency gives the number of postings, the number of postings gives the gap size if gaps are assumed equal, and the gap size gives the gamma code length. Summing over all terms gives the size.
Write $N$ for the number of documents, $M$ for the number of distinct terms, and $L$ for the average number of tokens in a document.
- Relative frequencies. By Zipf's law the collection frequency of the term of rank $i$ is proportional to $1/i$. Write its share of all tokens as $c/i$. The shares sum to 1, so $c \sum_{i=1}^{M} 1/i = c\,H_M = 1$, where $H_M$ is the $M$th harmonic number, and $c = 1/H_M \approx 1/\ln M$. For RCV1, $M = 400{,}000$ and $\ln M = 12.9$, which the text rounds to $c \approx 1/13$. (The approximation is the text's. The exact value is $H_M = 13.48$, since $H_M$ is about $\ln M + 0.577$.)
- Occurrences per document. A document of $L$ tokens contains the term of rank $i$ an expected $Lc/i$ times. For RCV1, $L = 200$ and $Lc = 200/13 \approx 15$, so the term of rank $i$ occurs about $15/i$ times per document.
- Blocks of terms. Cut the ranked vocabulary into blocks of $Lc$ terms: block $j$ holds the ranks from $(j-1)Lc + 1$ to $jLc$. A term in block $j$ has rank $i \le jLc$, so it occurs at least $Lc/(jLc) = 1/j$ times per document on average. The estimate takes this lower bound and reads it as the fraction of documents that contain the term. A term in block $j$ then has $N/j$ postings.
- Equal gaps. Assume the $N/j$ postings of a term in block $j$ are spread evenly over the $N$ documents. Every gap of the term is then $j$.
- Bits for one term. A gap of $j$ takes $2\lfloor \log_2 j \rfloor + 1 \approx 2\log_2 j$ bits, so the postings list of one term in block $j$ takes about $(N/j) \times 2\log_2 j$ bits.
- Bits for the index. A block has $Lc$ terms and there are $M/(Lc)$ blocks, so the postings take about
$$\sum_{j=1}^{M/(Lc)} Lc \cdot \frac{2N\log_2 j}{j} \ \text{bits}.$$
For RCV1, $N = 800{,}000$, $Lc = 15$ and $M/(Lc) = 400{,}000/15 \approx 26{,}667$ blocks. The sum $\sum_{j \le 26{,}667} (\log_2 j)/j$ is 74.8, so the total is $2 \times 800{,}000 \times 15 \times 74.8 \approx 1.80 \times 10^{9}$ bits, or 224 megabytes, the figure the text reports (it rounds the number of blocks to 27,000, for which the sum gives 225). The measured size of the gamma-coded RCV1 index is 101 megabytes. The text gives two reasons for the gap between them: Zipf's law is not a close description of RCV1's term frequencies, and gaps are not all the same size.
The same derivation on Reuters-21578 uses $N = 10{,}788$, $M = 29{,}187$ and $L = 1{,}330{,}267 / 10{,}788 = 123.3$ tokens per story. Then $H_M = 10.86$, $Lc = 123.3/10.86 = 11.36$, and there are $29{,}187 / 11.36 \approx 2{,}570$ blocks. The sum gives 1.36 megabytes, or 1.39 with the exact length $2\lfloor \log_2 j \rfloor + 1$ in step 5, against the 0.783 megabytes measured below. The estimate is 1.7 times too large, where for RCV1 it was 2.2 times too large. One cause is visible in the counts. Step 3 counts a term's occurrences as if each fell in a different document, and the model so predicts 1.03 million postings. The collection has 725,793, because a term that occurs in a story occurs there 1.83 times on average. The estimate gives the order of magnitude of the index, not a prediction of its size.
Beyond gamma: delta, Golomb and Rice codes
Codes that encode the length itself more efficiently, such as the delta codes of Elias (1975), do better for large gaps. A delta code writes the number of binary digits of $G$ as a gamma code, followed by the same offset. For 1467, which has 11 binary digits, that is the gamma code of 11, 1110011, followed by the 10-bit offset 0110111011. The result is 17 bits instead of gamma's 21. With $k = \lfloor \log_2 G \rfloor$, the gap has $k + 1$ binary digits, so the delta code takes $2\lfloor \log_2 (k+1) \rfloor + 1 + k$ bits. The delta codes of palladium's five gaps, bit by bit:
| Gap | Binary digits | Gamma code of that count | Offset | Delta code | Bits |
|---|---|---|---|---|---|
| 1467 | 11 | 1110011 |
0110111011 |
11100110110111011 |
17 |
| 54 | 6 | 11010 |
10110 |
1101010110 |
10 |
| 271 | 9 | 1110001 |
00001111 |
111000100001111 |
15 |
| 3 | 2 | 100 |
1 |
1001 |
4 |
| 6284 | 13 | 1110101 |
100010001100 |
1110101100010001100 |
19 |
The list takes 65 bits as delta codes, against 77 as gamma codes and 64 as variable bytes. To decode the first delta code, read a gamma code: 1110011 is 11. The gap therefore has 11 binary digits, so read 10 more bits, 0110111011, and restore the leading 1 to get 10110111011, which is 1467.
For small gaps delta can be slightly longer: 2 takes 3 bits in gamma and 4 in delta. Comparing the two length formulas for every gap, the delta code is one bit longer for the gaps 2, 3 and 8 to 15, the same length for 1, 4 to 7 and 16 to 31, and shorter for every gap from 32 on (checked by the script up to $2^{20}$). The course text's Exercise 5.9 defines a variant of the delta code that gamma-codes the length of the offset, not the number of binary digits. Its code lengths differ from the delta lengths given here.
Golomb codes (Golomb, 1966) take a parameter $b$ fitted to each list. Write $G - 1 = qb + r$ with $0 \le r < b$. The code is the quotient $q$ in unary, as $q$ ones and a zero, followed by the remainder $r$ in truncated binary: with $c = \lceil \log_2 b \rceil$, the first $2^c - b$ remainders are written in $c - 1$ bits, and each other remainder $r$ is written as the number $r + 2^c - b$ in $c$ bits. For $b = 7$, $c = 3$ and $2^3 - 7 = 1$: the remainder 0 is 00, and the remainders 1 to 6 are 010 to 111. The gap 54 has $53 = 7 \times 7 + 4$, so its code is seven 1s and a 0 followed by 101, 11 bits. A decoder reads $c - 1$ bits and reads one more only if their value is at least $2^c - b$.
A Rice code is the special case $b = 2^k$, where no remainder is shortened: the remainder takes exactly $k$ bits and the whole code takes $q + 1 + k$. For the gap 54 with $k = 5$: $53 = 1 \times 32 + 21$, so the code is 10 followed by 10101, 7 bits, against 11 for gamma and 8 for VB. Golomb codes with a well-chosen $b$ are optimal prefix codes when gaps follow a geometric distribution (Gallager and Van Voorhis, 1975), as they do when a term's documents are scattered at random through the collection. (Maximum Entropy Distributions proves that the geometric distribution has the greatest entropy among distributions on the positive integers with a given mean, and compares it with the gaps of one Reuters term.) A good $b$ is then about 0.69 times the mean gap (Witten, Moffat, and Bell, 1999; Pibiri and Venturini, 2021, §2.4), and Rice codes, restricted to powers of two, come close.
On the two lists the fitted parameter pays off:
- Palladium's mean gap is $8079/5 = 1{,}616$, and $0.69 \times 1{,}616 = 1{,}115$, nearest to $2^{10}$. With $k = 10$ the five codes take 12, 11, 11, 11 and 17 bits, 62 in all, fewer than VB's 64 and the delta code's 65. For example, $1467 - 1 = 1 \times 1024 + 442$ gives
10followed by0110111010. - Oil's mean gap is 10.4, and $0.69 \times 10.4 = 7.2$, nearest to $2^3$. With $k = 3$ the whole list of 1,038 postings takes 5,000 bits, 4.82 per posting, against 5,728 for gamma and 6,085 for delta. Of the Rice parameters $k = 0$ to 6, $k = 3$ gives the smallest total.
The price is that the parameter must be stored with each list and chosen before encoding, which is what the parameter-free gamma and delta codes avoid. These totals are observations on two lists, not a comparison over the collection.
Measured on a whole collection
Two lists can mislead, so which code wins over a whole index? Of the three codes, delta is the smallest, then gamma, then variable byte. Applying each code to every postings list of Reuters-21578, 725,793 postings in all, gives the following sizes (megabytes of a million bytes, rounded to three decimals; bits per posting rounded to two):
| Encoding of the docIDs | Size | Bits per posting |
|---|---|---|
| 32-bit integers | 2.903 MB | 32.00 |
| Fixed 14-bit integers, the fewest that can hold 10,788 | 1.270 MB | 14.00 |
| VB on the docIDs themselves, no gaps | 1.445 MB | 15.93 |
| VB on gaps | 0.868 MB | 9.57 |
| Gamma on gaps | 0.783 MB | 8.63 |
| Delta on gaps | 0.733 MB | 8.08 |
| zlib (level 9) on the 32-bit gaps | 0.909 MB | 10.02 |
Several lessons are in the table.
- Gaps matter more than the choice of code. VB on raw docIDs saves half; VB on gaps saves 70 percent.
- Even the simplest gap code beats a fixed-width encoding sized exactly to the collection.
- A general-purpose compressor does worse. zlib, which knows nothing of the structure of postings, loses to every integer code on gaps, despite working much harder.
The delta code is the smallest of the three, at 8.08 bits per posting, 0.90 bits above the 7.19-bit entropy of the pooled gap distribution computed above.
The averages hide a strong dependence on the term.
Example (terms in a thousand or more stories). For terms that occur in a thousand or more stories, gamma is smaller than variable byte by a wide margin: 3.4 bits per posting against 8. In those lists two thirds of the gaps are 1, 2, or 3. Gamma spends 1 to 3 bits on each, while variable byte cannot go below 8. The figure groups terms by document frequency:
The crossover is at document frequencies of about a hundred. Below it variable byte is smaller, and from the 100 to 999 band upward gamma is. Rare terms, which make up most of the dictionary, cost gamma more. Frequent terms, which hold most of the postings, cost it much less. The size of an index is dominated by its long lists, so the code that is better on long lists wins. That is the Zipf's law skew at work.
Size against speed
Gamma wins on size. Does it also win on speed? Usually not. Bit-level codes produce smaller indexes, but decoding them means extracting individual bits, which processors do slowly. Scholer, Williams, Yiannis, and Zobel (2002) found that byte-aligned codes gave faster query processing than bit-aligned ones despite being larger. Decoding speed mattered more than the size difference. Later work has pushed further in the same direction, toward codes designed for how processors actually work:
- Word-aligned codes such as Simple-9 pack as many small gaps as fit into each 32-bit word, using a few bits of the word to say how they are packed (Anh and Moffat, 2005).
- PForDelta encodes blocks of, typically, 128 gaps with a fixed bit width chosen to fit most of them. It stores the few large exceptions separately, so that most values can be decoded with no branching (Zukowski, Héman, Nes, and Boncz, 2006).
- SIMD codecs decode several integers at once using the vector instructions of modern processors, reaching billions of integers per second (Lemire and Boytsov, 2015).
Pibiri and Venturini (2021) survey these and other methods. Modern postings compression works these codes, and the Elias–Fano representation, bit by bit on the Reuters-21578 postings of this article. Production search engines typically use block-based codes of this kind. Lucene's postings format, for example, stores the delta between consecutive docIDs, which is the gap of this article, in packed blocks of fixed bit width, with skip data between blocks (Apache Software Foundation, Lucene documentation). Such engines often combine the codes with skip information that lets a query jump over blocks it does not need, which connects compression to the skip pointers used in postings intersection.
Making gaps smaller
Every code above takes the gaps as given. Can the gaps themselves be made smaller? They can, because they depend on how docIDs are assigned. If documents that share many terms receive nearby docIDs, the postings lists of those terms contain runs of small gaps, which compress better. DocID reassignment reorders the collection before indexing. It may cluster similar documents or, on the web, sort pages by URL so that pages from the same site are adjacent (Silvestri, 2007). Reassignment can substantially reduce index size without changing any code.
Reuters-21578 shows the effect in a mild form. Its stories are numbered roughly in filing order, so stories about the same event tend to be near each other. What happens if that order is destroyed? Shuffling the docIDs into a random order, with 30 different random seeds, raises the gamma-coded size from 0.783 to a median of 0.815 megabytes (interquartile range 0.815 to 0.816), about 4 percent. The VB size rises from 0.868 to a median of 0.876 megabytes. Filing order is a weak form of clustering. Orderings designed to put similar documents together, such as the URL sorting described above, are what produce the large savings.
The same gap technique applies to the positions in a positional index. Positions within a document are stored as gaps between successive occurrences. Term frequencies, which are mostly small numbers, are encoded with the same variable-length codes.
All of this compression is lossless, and it applies unchanged to any index whose postings are sorted integers. The vector indexes used for retrieval with learned embeddings are compressed differently: product quantization replaces each vector by a short code and loses information, so it belongs with the lossy methods of the first section (Jégou, Douze, and Schmid, 2011). Vector Search on Disk and with Filters trains a refinement of it, the anisotropic quantization behind ScaNN, and keeps the full vectors on a solid-state drive for a graph index.
Summary
| Structure | Method | RCV1 size |
|---|---|---|
| Postings (docIDs) | 32-bit integers | 400 MB |
| Variable byte codes on gaps | 116 MB | |
| Elias gamma codes on gaps | 101 MB |
The uncompressed postings size is computed in this article. The compressed postings sizes are those reported by Manning, Raghavan, and Schütze (2008, §5.3). The dictionary's rows of this table, 11.2 megabytes down to 5.9, are in Dictionary Compression.
Compression is what makes many other design decisions affordable. It is one reason web engines can keep stop words in the index, since their long lists of small gaps compress to very little. It also lets a large share of a production index be served from memory, as described in search at scale.
Worked problems
The first three problems are exercises from chapter 5 of the course text (Manning, Raghavan, and Schütze, 2008), restated here with their data and solved in our own words. The fourth is posed on this article's palladium list. The exercise on dictionary block sizes is worked in Dictionary Compression. The script tools/experiments/indexing/compression_examples.py checks every code and total.
Problem 1 (Exercise 5.5 of the course text). Compute the variable byte and gamma codes for the postings list 777, 17743, 294068, 31251336, using gaps where possible, and write the binary codes in 8-bit blocks.
Solution. The first entry has no predecessor and is encoded as it stands. The other three become gaps: $17743 - 777 = 16966$, $294068 - 17743 = 276325$, and $31251336 - 294068 = 30957268$. The variable byte codes take 12 bytes:
| Number | Binary | 7-bit groups | VB code |
|---|---|---|---|
| 777 | 1100001001 |
0000110 0001001 |
00000110 10001001 |
| 16966 | 100001001000110 |
0000001 0000100 1000110 |
00000001 00000100 11000110 |
| 276325 | 1000011011101100101 |
0010000 1101110 1100101 |
00010000 01101110 11100101 |
| 30957268 | 1110110000101111011010100 |
0001110 1100001 0111101 1010100 |
00001110 01100001 00111101 11010100 |
For the gamma codes, drop the leading 1 of each binary form to get the offset, and write the offset's length in unary:
| Number | Offset | Unary length | Bits |
|---|---|---|---|
| 777 | 100001001 (9 bits) |
nine 1s and a 0 | 19 |
| 16966 | 00001001000110 (14 bits) |
fourteen 1s and a 0 | 29 |
| 276325 | 000011011101100101 (18 bits) |
eighteen 1s and a 0 | 37 |
| 30957268 | 110110000101111011010100 (24 bits) |
twenty-four 1s and a 0 | 49 |
The four codes take $19 + 29 + 37 + 49 = 134$ bits. Written one after another in 8-bit blocks, with two zero bits of padding in the last block, they fill 17 bytes:
11111111 10100001 00111111 11111111 10000010 01000110 11111111 11111111
11000001 10111011 00101111 11111111 11111111 11111011 01100001 01111011
01010000
With gaps this large the gamma code is the longer one, 134 bits against 96, as the table of ranges above predicts for gaps of 256 and more.
Problem 2 (Exercise 5.6). The postings list 4, 10, 11, 12, 15, 62, 63, 265, 268, 270, 400 has the gaps 4, 6, 1, 1, 3, 47, 1, 202, 3, 2, 130. With variable byte encoding, find the largest gap that fits in one byte, the largest that fits in two, and the number of bytes the list needs.
Solution. The answers are 127, 16,383, and 13 bytes. One byte carries 7 data bits, so the largest one-byte gap is $2^7 - 1 = 127$. Two bytes carry 14, so the largest two-byte gap is $2^{14} - 1 = 16{,}383$. Of the eleven gaps, 202 and 130 exceed 127 and take two bytes each. The other nine take one byte each. The total is $9 + 2 \times 2 = 13$ bytes, 104 bits. For comparison, the gamma codes of the same gaps take $5 + 5 + 1 + 1 + 3 + 11 + 1 + 15 + 3 + 3 + 15 = 63$ bits, since most of these gaps are below 16.
Problem 3 (Exercise 5.8). Reconstruct the gaps and then the postings from the gamma-coded sequence 1110001110101011111101101111011.
Solution. The gaps are 9, 6, 3, 59, 7 and the postings are 9, 15, 18, 77, 84. Decode one code at a time: count 1s up to the first 0, read that many offset bits, and restore the leading 1.
| Unary length | Offset | Binary with leading 1 | Gap |
|---|---|---|---|
1110 |
001 |
1001 |
9 |
110 |
10 |
110 |
6 |
10 |
1 |
11 |
3 |
111110 |
11011 |
111011 |
59 |
110 |
11 |
111 |
7 |
The five codes use $7 + 5 + 3 + 11 + 5 = 31$ bits, the whole sequence. Adding up the gaps gives the postings: 9, $9 + 6 = 15$, $15 + 3 = 18$, $18 + 59 = 77$, $77 + 7 = 84$.
Problem 4. Decode the delta-coded stream of palladium, 11100110110111011 1101010110 111000100001111 1001 1110101100010001100 (written here with spaces between the codes, which the stored stream does not have), and recover the docIDs.
Solution. The docIDs are 1467, 1521, 1792, 1795, 8079. Each delta code starts with a gamma code that gives the number of binary digits of the gap.
1110011is the gamma code of 11. Read $11 - 1 = 10$ offset bits,0110111011, and restore the leading 1:10110111011is 1467.11010is the gamma code of 6. The 5 offset bits10110give110110, which is 54.1110001is the gamma code of 9. The 8 offset bits00001111give100001111, which is 271.100is the gamma code of 2. The single offset bit1gives11, which is 3.1110101is the gamma code of 13. The 12 offset bits100010001100give1100010001100, which is 6284.
The decoder knew where each code ended without the spaces: the gamma code is prefix-free, and it announces exactly how many bits follow. Adding up the gaps: 1467, $1467 + 54 = 1521$, $1521 + 271 = 1792$, $1792 + 3 = 1795$, $1795 + 6284 = 8079$.
What we have learned
An index can shrink to about a quarter of its size, or less, without losing anything. The dictionary shrinks by a change of layout, the subject of Dictionary Compression. The postings shrink because sorted lists become gaps, and gaps are mostly small. Variable byte spends whole bytes and decodes fast. Gamma spends bits, loses on rare terms like palladium, and wins overall because frequent terms like oil hold most of the postings. Its expected length is at most $2H + 1$ bits for any distribution of gaps with entropy $H$ in which smaller gaps are at least as probable as larger ones. On Reuters-21578, variable byte on gaps took the postings from 2.903 to 0.868 megabytes, and the delta code reached 0.733.
The index of this topic now exists, at scale and compactly. The last article of the topic, Building an Indexing Pipeline, goes back from algorithms to code. It follows the decisions that an ordinary indexer written for a course assignment makes, often without naming them, and measures each one on Reuters-21578.
References
- Anh, V. N., and Moffat, A. (2005). Inverted index compression using word-aligned binary codes. Information Retrieval, 8(1), 151–166. record · 2 pages
- Apache Software Foundation. Apache Lucene core documentation: index file formats (postings). https://lucene.apache.org/core/ record · 7 pages
- Carmel, D., Cohen, D., Fagin, R., Farchi, E., Herscovici, M., Maarek, Y. S., and Soffer, A. (2001). Static index pruning for information retrieval systems. In Proceedings of SIGIR 2001, 43–50. record
- Cover, T. M., and Thomas, J. A. (2006). Elements of Information Theory, 2nd edition, sections 5.3 and 5.5. Wiley. record · 8 pages
- Elias, P. (1975). Universal codeword sets and representations of the integers. IEEE Transactions on Information Theory, 21(2), 194–203. record · 2 pages
- Gallager, R. G., and Van Voorhis, D. C. (1975). Optimal source codes for geometrically distributed integer alphabets. IEEE Transactions on Information Theory, 21(2), 228–230. record
- Golomb, S. W. (1966). Run-length encodings. IEEE Transactions on Information Theory, 12(3), 399–401. record
- Jégou, H., Douze, M., and Schmid, C. (2011). Product quantization for nearest neighbor search. IEEE Transactions on Pattern Analysis and Machine Intelligence, 33(1), 117–128. record · 6 pages
- Lemire, D., and Boytsov, L. (2015). Decoding billions of integers per second through vectorization. Software: Practice and Experience, 45(1), 1–29. record · 2 pages
- Lewis, D. D. (1997). Reuters-21578 text categorization test collection, distribution 1.0. record · 11 pages
- Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, chapter 5. Cambridge University Press. record · 102 pages
- Pibiri, G. E., and Venturini, R. (2021). Techniques for inverted index compression. ACM Computing Surveys, 53(6), article 125. record · 3 pages
- Scholer, F., Williams, H. E., Yiannis, J., and Zobel, J. (2002). Compression of inverted indexes for fast query evaluation. In Proceedings of SIGIR 2002, 222–229. record
- Silvestri, F. (2007). Sorting out the document identifier assignment problem. In Proceedings of ECIR 2007, 101–112. record
- Witten, I. H., Moffat, A., and Bell, T. C. (1999). Managing Gigabytes: Compressing and Indexing Documents and Images, 2nd edition. Morgan Kaufmann. record
- Zukowski, M., Héman, S., Nes, N., and Boncz, P. (2006). Super-scalar RAM-CPU cache compression. In Proceedings of ICDE 2006, 59. record · 2 pages
Reviewed: verified, 16 Nov 2026 · checked against sources, 23 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 12 revisions