Compressing postings lists
How to reduce the space of inverted-index postings lists using gap (d-gap) encoding plus integer codes (variable-byte, Elias gamma/delta, Golomb/Rice, Frame-of-Reference and block methods), their trade-offs for compression and decoding speed, and worked examples including Python code.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Compressing postings lists reduces the disk and memory used by an inverted index and speeds up I/O when answering queries. Engineers use these methods in search engines and IR systems (see "inverted index" and "Text compression" topics) to trade off storage, sequential decoding speed, and random-access (skip) support.
Key ideas
- d-gap (gap) encoding: replace the postings list of docIDs d1, d2, d3, ... (sorted) by the first docID and the differences (gaps): g1 = d1, gi = di - d_{i-1} for i>1. This reduces average value size because gaps are smaller than absolute docIDs. To draw: left column list docIDs (e.g. 3, 6, 10...) with arrows to a right column list of gaps (3,3,4...). Label arrows "subtract previous".
- Integer compression (universal codes): represent small positive integers (gaps) with bit patterns that use fewer bits for small numbers and more bits for larger numbers. Common codes:
- Variable-byte (VB) coding: store 7 data bits per byte; the most significant bit (MSB) is a continuation bit (0 if more bytes follow, 1 for final byte) or the opposite variant. The number of bytes is ceil((floor(log2(n))+1)/7). This is fast to decode byte-wise.
- Elias gamma code (unary+binary): for integer x >= 1, write unary length (floor(log2(x)) zeros and a 1), then append the remaining (floor(log2(x))) bits of x (binary without the leading 1). Gamma is compact for small numbers; exact length in bits is 2*floor(log2(x)) + 1. Draw: write a row with zeros then 1, below it write the binary remainder bits aligned to the right.
- Elias delta code: gamma-encode the length N = floor(log2(x)) + 1, then write the lower N-1 bits of x. Total bits = (2*floor(log2(N)) + 1) + (N - 1), where N = floor(log2(x)) + 1.
- Golomb / Rice codes: parameterised by divisor M. Rice codes are Golomb with M a power of two. Good when gaps follow geometric-like distributions.
- Frame-of-Reference (FOR) / binary packing: divide postings into blocks of size B, choose a base (often the block minimum), store each value as a fixed-width integer with bit-width b = ceil(log2(max-min+1)). This gives good SIMD-friendly decoding and random block skipping.
- Simple9 / Simple16: pack multiple small integers into a 32-bit word using a selector. PForDelta (and variants like FastPFOR) use block-based fixed bit-width plus exceptions (patched) for outliers. These are CPU-friendly and widely used in practice.
- Block-based compression and skipping: to allow random-access or fast skipping, compress postings in blocks (e.g. 128 docIDs). Maintain for each block metadata (first docID, last/max docID, byte offset) or skip pointers so that queries (especially AND) can jump blocks instead of decoding whole lists.
- Trade-offs:
- Gamma/delta give smaller bit-size for very small integers but are bit-oriented and slower to decode than VB or FOR.
- VB is byte-oriented and fast; FOR and SIMD-friendly schemes give best decoding throughput on modern CPUs.
- Block size affects compression ratio vs random-access: larger blocks compress better but make skipping more costly.
Assumptions behind main derivations: postings are sorted integers > 0; we compress gaps (positive integers). For Elias codes x>=1.
Formulas
g1 = d1 — first gap equals first docID. g_i = d_i - d_{i-1} — gap definition. Symbols: d_i = i-th docID (unitless index), g_i = i-th gap (unitless), applies when docIDs sorted ascending.
VB_bytes(n) = ceil((floor(log2(n)) + 1) / 7) — number of bytes used by Variable-Byte for integer n>=1. log2 is binary logarithm; applies for the VB variant which stores 7 data bits per byte.
len_gamma(x) = 2*floor(log2(x)) + 1 — length in bits of Elias gamma code for integer x >= 1.
len_delta(x) = (2*floor(log2(N)) + 1) + (N - 1), where N = floor(log2(x)) + 1 — length in bits of Elias delta code for x>=1.
FOR_bits_per_value = ceil(log2(max_in_block - min_in_block + 1)) — bits stored per value in a block after subtracting base.
Worked examples
Example 1 — numeric + Variable-Byte (VB) encoding Given postings list: [3, 6, 10, 15, 16, 100] Steps:
- Compute gaps: g1 = 3; g2 = 6-3 = 3; g3 = 10-6 = 4; g4 = 15-10 = 5; g5 = 16-15 = 1; g6 = 100-16 = 84. So gaps = [3,3,4,5,1,84].
- Encode each gap with VB (7 data bits per byte, MSB=1 marks final byte of that integer):
- 3 in binary fits in 7 bits -> single byte: 0x80 | 0x03 = 0x83 (131 decimal).
- 3 -> 0x83 (131).
- 4 -> 0x84 (132).
- 5 -> 0x85 (133).
- 1 -> 0x81 (129).
- 84 -> 0x80 | 0x54 = 0xD4 (212).
- Final encoded byte sequence (decimal): [131, 131, 132, 133, 129, 212]. Bold final answer: [131, 131, 132, 133, 129, 212].
Example 2 — Elias gamma coding (bit-level) of the same gaps We show each gap's gamma code (unary(length) + remainder bits):
- x=3: floor(log2(3))=1 -> unary: "01" (one zero then 1). Binary 3 = "11", remainder = last 1 bit "1". Gamma code = "01" + "1" = "011" (3 bits).
- x=3 -> same "011".
- x=4: floor(log2(4))=2 -> unary: "001". Binary 4 = "100", remainder "00". Code = "00100" (5 bits).
- x=5: floor(log2(5))=2 -> unary: "001". Binary 5 = "101", remainder "01". Code = "00101" (5 bits).
- x=1: floor(log2(1))=0 -> unary: "1". Binary 1 = "1", remainder "" (zero bits). Code = "1" (1 bit).
- x=84: floor(log2(84))=6 -> unary: "0000001". Binary 84 = "1010100", remainder "010100" (6 bits). Code = "0000001" + "010100" = "0000001010100" (13 bits). Concatenate (for a stream) gives a bitstring; total bits = 3 + 3 + 5 + 5 + 1 + 13 = 30 bits.
Example 3 — Python program: gap encoding + Variable-Byte encode/decode Code (Python 3):
# gap_vb.py - gap encode and variable-byte encode
def gap_encode(docids):
if not docids:
return []
gaps = [docids[0]]
for i in range(1, len(docids)):
gaps.append(docids[i] - docids[i-1])
return gaps
def vb_encode_number(n):
# returns list of byte values (0-255)
bytes_out = []
while True:
b = n & 0x7F
n >>= 7
if n == 0:
bytes_out.append(0x80 | b) # set MSB = 1 for last byte
break
else:
bytes_out.append(b) # MSB = 0
return bytes_out
def vb_encode_list(numbers):
out = []
for n in numbers:
out.extend(vb_encode_number(n))
return out
# Example usage
if __name__ == '__main__':
docs = [3, 6, 10, 15, 16, 100]
gaps = gap_encode(docs)
vb = vb_encode_list(gaps)
print('docIDs:', docs)
print('gaps :', gaps)
print('vb bytes:', vb)
Sample input: run the script (no stdin required). Sample exact output when run (Python 3):
docIDs: [3, 6, 10, 15, 16, 100] gaps : [3, 3, 4, 5, 1, 84] vb bytes: [131, 131, 132, 133, 129, 212]
(These values match Example 1.)
Common mistakes
- Off-by-one when computing unary prefix in Elias gamma (number of leading zeros = floor(log2(x))).
- Confusing bit order or endianness when writing VB bytes; remember VB packs 7 least-significant bits first and sets MSB=1 on final byte in the common variant.
- Not considering integer overflow or choose incorrect block size for FOR leading to negative widths (ensure max-min+1 > 0).
- Comparing compression ratios without specifying whether headers/skip pointers or block metadata are included.
For your exam
Types of questions you will see:
- Definitions: define postings list, d-gap, variable-byte, Elias gamma/delta, FOR.
- Full-marks answer includes the formal definition and a small example.
- Short notes: advantages/disadvantages of VB vs gamma vs FOR; how block size affects trade-offs.
- Include computational complexity of decode (sequential decode cost) and random-access behavior.
- Derivations: show formula for gamma code length and derive delta length. Show step-by-step how gamma code is built.
- Include the assumption x>=1 and show unary + binary decomposition.
- Numericals: given a postings list, compute gaps and produce VB bytes or gamma bitstring.
- Show all steps, binary representations, and final bytes/bitstring.
- Programming: implement gap + VB encode/decode in Python or C.
- Full marks: correct code, demonstration with sample input/output, complexity analysis.
- Diagrams: draw postings list and gaps; draw block layout for FOR with base and fixed bit-width columns.
- Label axes: index vs value, byte offsets, block boundaries, first docID per block.
Quick check
- What is the gap value sequence for docIDs [7, 10, 20]?
- How many bits does Elias gamma use to code x = 16?
- For Variable-Byte coding, how many bytes are needed to encode integer 2000? Answers: 1) [7, 3, 10] 2) 2floor(log2(16)) + 1 = 24 + 1 = 9 bits 3) floor(log2(2000))+1 = 11 bits -> bytes = ceil(11/7) = 2 bytes; with our VB variant, the actual bytes are [80, 143]
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?