Sub topic 6
Encodings: dictionary, run-length, and delta
This chapter assumes you know the layout from the previous chapters: a file holds row groups, a row group holds one column chunk per column, and a column chunk is a sequence of pages. You should also be comfortable reading short PyArrow scripts.
Encoding versus compression
Parquet shrinks data in two separate steps. Each page's values are first encoded, then the encoded bytes are compressed with a codec such as Snappy or Zstandard.
An encoding is a type-aware transformation. It knows the values are integers, or strings, or booleans, and it exploits patterns such as repetition or small differences between neighbors. A codec is type-blind. It sees bytes and looks for repeated byte sequences.
Encoding often shrinks data far more than a codec can, and it makes the codec's job easier. The two steps stack.
Plain encoding
PLAIN is the baseline. Fixed-width types are written back to back: an int64 takes 8 bytes per value. Strings are written as a 4-byte length followed by the bytes. Every other encoding is judged against it.
Dictionary encoding
Dictionary encoding replaces each value with a small integer index into a table of distinct values.
- The writer collects the distinct values of a column chunk into a dictionary page, stored at the start of the chunk.
- Each data page then stores only the indices.
- The indices are written with the RLE/bit-packing hybrid described below, using just enough bits for the dictionary size.
A column of country names with 200 distinct values needs 8 bits per row, however long the names are. A column with 4 distinct values needs 2 bits per row.
Writers apply dictionary encoding by default, and they apply it adaptively. PyArrow keeps a dictionary for a column chunk until it reaches a size limit, which is 1 MiB by default. Once the limit is exceeded, the writer falls back to PLAIN for the remaining pages. A column of unique IDs hits that limit almost immediately. The chunk then contains a wasted dictionary plus plain pages, and its metadata lists both encodings.
Dictionary encoding suits low and medium cardinality columns. Those are columns where the number of distinct values is small relative to the number of rows, such as status codes, countries, and categories. It also helps long strings that repeat.
Run-length and bit-packing
Parquet's RLE encoding is really a hybrid of two techniques. The writer chooses between them on the fly.
- Run-length: a run of identical values is stored as a count and one value. A thousand consecutive
3s become "1000 × 3". - Bit-packing: groups of 8 values are packed using the minimum number of bits per value.
The hybrid appears in three places: dictionary indices, boolean columns, and the definition and repetition levels that track nulls and nesting. The levels are covered in a later chapter.
Run-length only pays off when equal values sit next to each other, so row order matters. If the same four categories cycle a, b, c, d, a, b, ..., the indices form no runs and the writer bit-packs them. If the rows are sorted by category, the same data becomes four long runs. Sorting a table before writing is one of the cheapest ways to improve compression.
Delta encoding
Delta encodings store differences between consecutive values instead of the values themselves. Differences are small when the data changes slowly, and small numbers need few bits.
DELTA_BINARY_PACKED is for int32 and int64 columns. Take the values 1000, 1003, 1004, 1010:
- Store the first value,
1000. - Store the deltas:
3, 1, 6. - Within each block of values, subtract the block's minimum delta (here
1), leaving2, 0, 5. - Bit-pack the remainders using the smallest width that fits (3 bits here).
Sequential IDs, timestamps with regular spacing, and counters work well. An ID column of 0, 1, 2, ... has a constant delta, so every remainder is zero and the column takes almost no space.
Two related encodings handle byte arrays such as strings:
DELTA_LENGTH_BYTE_ARRAYstores all string lengths as delta-packed integers, followed by the concatenated bytes.DELTA_BYTE_ARRAYstores, for each string, the length of the prefix it shares with the previous string plus the remaining suffix. It suits sorted strings such as URLs, file paths, and keys.
For floating-point columns, BYTE_STREAM_SPLIT writes the first byte of every value, then the second byte, and so on. It does not shrink data by itself. It groups similar bytes together so the codec compresses them better.
Summary of encodings
| Encoding | Data it suits | Needs to work well |
|---|---|---|
| PLAIN | Anything | Nothing. It is the fallback. |
| Dictionary (RLE_DICTIONARY) | Repeated values of any type | Moderate number of distinct values |
| RLE / bit-packed hybrid | Indices, booleans, levels | Runs of equal values for the RLE part |
| DELTA_BINARY_PACKED | Integers, timestamps | Small differences between neighbors |
| DELTA_BYTE_ARRAY | Strings | Shared prefixes, ideally sorted |
| BYTE_STREAM_SPLIT | Floats and doubles | A good codec applied afterward |
Comparing encodings with PyArrow
The script below writes the same data several ways. It uses compression="none" so the file sizes show only the effect of the encoding. It then prints the encodings recorded in the footer.
import os
import pyarrow as pa
import pyarrow.parquet as pq
table = pa.table({
"id": list(range(1_000_000)),
"category": ["a", "b", "c", "d"] * 250_000,
})
sorted_table = table.sort_by("category")
variants = {
"plain": (table, dict(use_dictionary=False)),
"dictionary": (table, dict(use_dictionary=True)),
"dictionary_sorted": (sorted_table, dict(use_dictionary=True)),
"delta_id": (
table,
dict(use_dictionary=False, column_encoding={"id": "DELTA_BINARY_PACKED"}),
),
}
for name, (data, options) in variants.items():
path = f"enc_{name}.parquet"
pq.write_table(data, path, compression="none", **options)
print(name, os.path.getsize(path), "bytes")
row_group = pq.ParquetFile(path).metadata.row_group(0)
for i in range(row_group.num_columns):
col = row_group.column(i)
print(" ", col.path_in_schema, col.encodings)Expect these results. Exact sizes and encoding names depend on your PyArrow version.
plainis the largest. Theidcolumn alone takes about 8 MB, andcategoryadds a length prefix to every value.dictionaryshrinkscategoryto a small fraction of its plain size. Itsidcolumn falls back to plain pages because the IDs overflow the dictionary limit. The encodings list foridshows both dictionary and plain entries.dictionary_sortedmakescategoryshrink further, because the indices now form four long runs.delta_idmakesidshrink from about 8 MB to a few kilobytes, because every delta is 1.
Reading dictionary columns efficiently
A reader must decode dictionary indices back into values. For string columns, that means allocating and copying many repeated strings. PyArrow can skip this and keep the column dictionary-encoded in memory:
import pyarrow.parquet as pq
result = pq.read_table("enc_dictionary.parquet", read_dictionary=["category"])
print(result.schema.field("category").type)The column's type prints as a dictionary type instead of a plain string. This can cut memory use and speed up grouping and comparison on repetitive strings.
Edge cases and gotchas
- Dictionary on unique columns wastes work. For columns you know are unique, such as UUIDs, turn dictionary encoding off with
use_dictionary=Falseor a list of the columns that should keep it. The writer then skips building a dictionary it would discard. column_encodinghas conditions. In PyArrow, a per-column encoding such asDELTA_BINARY_PACKEDrequires dictionary encoding to be off for that column. Settinguse_dictionaryto a list of the other columns does this.- Dictionary pages are per column chunk. Each row group builds its own dictionary. A value that appears in every row group is stored once per row group, so smaller row groups mean more repeated dictionaries.
- Dictionaries affect memory on read. A very large dictionary has to be loaded before any data page in that chunk can be decoded.
- Row order is a tuning knob. Sorting by a low-cardinality column helps run-length, and sorting by a timestamp or key helps delta encoding and statistics. The cost is that only one sort order can be optimal at a time.
- Encodings do not change the logical data. Any reader decodes to identical values. Choose encodings for size and speed, not correctness.
- Delta encodings need reader support. Files that use
DELTA_*encodings need readers that implement them. Current mainstream libraries do, but very old tools may not.
Where this leads
Encodings reduce what is stored in each page. The next chapter looks at the codecs applied to the encoded bytes and at how their size and speed trade off.
Exercise
An integer column holds the values 100, 105, 105, 112. Under DELTABINARYPACKED, what first value and deltas are stored? After subtracting the minimum delta, what remainders are bit-packed, and how many bits does each need? Then explain why a column of random UUID strings gains little from dictionary encoding.
Show answer
The first value is 100 and the deltas are 5, 0, 7. The minimum delta is 0, so subtracting it leaves 5, 0, 7. The largest remainder is 7, which fits in 3 bits, so each remainder takes 3 bits. UUID strings are almost all distinct, so the dictionary would hold nearly one entry per row and exceed the size limit. The writer then falls back to plain pages, and the dictionary is wasted space.
Exercise
A table has a column "status" with 5 distinct values and 10 million rows, written in random order. You sort the table by "status" before writing. What happens to the dictionary indices, and why does the file shrink?
Show answer
The dictionary stays the same, with 5 entries. The indices change from a random sequence into 5 long runs of identical values. The RLE part of the hybrid encoding stores each run as a count and one value, so the indices take only a few bytes per page instead of about 3 bits per row.