Part 3 · Parquet and columnar files · Chapter 7
Nested data: repetition and definition levels
How Parquet stores structs, lists and maps in flat columns using the Dremel record shredding algorithm, how a reader reassembles records, the LIST and MAP logical types, and how Variant values are shredded into typed columns.
After this chapter you should be able to:
- Compute repetition and definition levels for a nested record by hand.
- Explain the three-level LIST and MAP logical type structure, and why lists need three levels.
- Explain how a reader rebuilds records, and why projecting one nested field is cheap.
- Read a shredded Variant column.
Chapters 5 and 6 dealt with flat columns, where each row has one value or a null. Real tables have structs, arrays and maps: an order with a list of line items, an event with a map of attributes. Parquet stores these in the same flat column chunks, one per leaf field, using the record shredding scheme from Google’s Dremel paper (Melnik et al., PVLDB 3(1), 2010).[Dremel] Each value in a leaf column carries two small integers, a repetition level and a definition level, and those two numbers are enough to rebuild the records.
This chapter works through the paper’s own example, then the LIST and MAP structures every modern writer produces, then Variant, the newest nested type. The shredder, assembler, writer and reader are in src/sim/parquet/nested.ts. The tests check the shredder against the levels printed in the Dremel paper, and check files both ways against Arrow C++ 26.0.1.
Levels
The README defines both levels in one paragraph:[README]
Definition levels specify how many optional fields in the path for the column are defined. Repetition levels specify at what repeated field in the path has the value repeated. The max definition and repetition levels can be computed from the schema (i.e. how much nesting there is).
The Dremel paper’s Document schema has every kind of field:
message Document {
required int64 DocId;
optional group Links {
repeated int64 Backward;
repeated int64 Forward;
}
repeated group Name {
repeated group Language {
required binary Code (STRING);
optional binary Country (STRING);
}
optional binary Url (STRING);
}
}
For each leaf, walk the path from the root. Max repetition is the number of repeated fields on the path; max definition is the number of fields that are not required (optional or repeated). Required fields add nothing, because they are always there.
| Leaf column | Path repetitions | Max r | Max d |
|---|---|---|---|
DocId | required | 0 | 0 |
Links.Backward | optional, repeated | 1 | 2 |
Links.Forward | optional, repeated | 1 | 2 |
Name.Language.Code | repeated, repeated, required | 2 | 2 |
Name.Language.Country | repeated, repeated, optional | 2 | 3 |
Name.Url | repeated, optional | 1 | 2 |
The levels’ meaning, for an entry in a leaf column:
- d is how far down the path the record is defined.
d = maxmeans a value is stored.d < maxmeans a NULL entry: the field at depthd + 1among the non-required fields is missing (if optional) or empty (if repeated). Only entries withd = maxhave a value in the page’s data section; “NULL values are not encoded in the data”.[README] - r says where this entry starts.
r = 0starts a new record.r = kmeans the entry repeats the k-th repeated field on the path, so a new element begins there, and every repeated field deeper than k starts a new list.
The max levels set the bit width of each level stream (chapter 6’s hybrid encoding). A column whose max level is 0 stores no levels at all: “If the column is not nested (i.e. the path to the column has length 1), we do not encode the repetition levels… For data that is required, the definition levels are skipped”.[README]
Q1. Leaf Name.Language.Country sits under repeated group Name, repeated group Language, and is itself optional. What are its max repetition and max definition levels?
Q2. In a column with max definition level 3, an entry has d = 1. What does that say?
Q3. In Name.Language.Code, an entry has r = 1. What happened?
Q4. optional group tags (LIST) { repeated group list { optional binary element } }. Which (r, d) entries do null, [] and [null] produce?
Shredding
The paper’s two records, in JSON:
{ "DocId": 10, "Links": { "Forward": [20, 40, 60] },
"Name": [ { "Language": [ { "Code": "en-us", "Country": "us" }, { "Code": "en" } ], "Url": "http://A" },
{ "Url": "http://B" },
{ "Language": [ { "Code": "en-gb", "Country": "gb" } ] } ] }
{ "DocId": 20, "Links": { "Backward": [10, 30], "Forward": [80] },
"Name": [ { "Url": "http://C" } ] }
Shredding walks each record depth first and writes to every leaf column it passes:
- A present value is written with the current r and the leaf’s max d.
- A repeated field writes its first element with the r it was given (its parent’s), and every later element with its own repetition depth. An empty repeated field writes nothing itself; go to rule 3.
- A missing optional field or empty repeated field writes one NULL entry into every leaf column below it, with the current r and the definition level of its parent. Every leaf column needs an entry for every record, or the reader could not line the columns up.
The book’s shredder is those three rules:
const writeField = (n: SNode, v: Json, r: number, d: number) => {
if (n.rep === 'repeated') {
const arr = (v ?? []) as Json[];
if (arr.length === 0) { emitNull(n, r, d); return; }
arr.forEach((e, i) => writeValue(n, e, i === 0 ? r : repDepth.get(n)!, d + 1));
} else if (n.rep === 'optional') {
if (v === null || v === undefined) emitNull(n, r, d);
else writeValue(n, v, r, d + 1);
} else {
writeValue(n, v, r, d); // required: must be present
}
};
and it produces the paper’s figure 3, which the tests check entry by entry:
Name.Language.Code Name.Language.Country Name.Url Links.Forward
value r d value r d value r d value r d
en-us 0 2 us 0 3 http://A 0 2 20 0 2
en 2 2 NULL 2 2 http://B 1 2 40 1 2
NULL 1 1 NULL 1 1 NULL 1 1 60 1 2
en-gb 1 2 gb 1 3 http://C 0 2 80 0 2
NULL 0 1 NULL 0 1
Read Name.Language.Code top to bottom. en-us starts record 1 (r 0). en repeats at level 2, the second Language of the same Name. The NULL at r 1, d 1 is the second Name: it repeats at level 1, and only Name is defined (it has no Language). en-gb is the third Name’s first Language, so it repeats at level 1. The final NULL starts record 2 (r 0), whose only Name has no Language. Country has the same r column, and a NULL at d 2 where en has a Language but no Country.
Name.Language.Country column, definition level 2 means Language exists but Country is missing. Level 1 means Name exists and its Language list is empty. Repetition level 0 marks each new document.[Dremel][Parquet format] parquet-java does this in MessageColumnIO’s record consumer. When a group ends, writeNullForMissingFieldsAtCurrentLevel writes nulls for each field that was not written, at the current repetition level and the group’s definition level; for a missing group it caches the repetition level and writes the nulls to all of the group’s leaves later. It also rejects an empty repeated field outright (“empty fields are illegal, the field should be ommited completely instead”), so an empty list reaches the leaves only as a missing field.[parquet-java] Arrow C++ computes the levels for a whole Arrow array at once in MultipathLevelBuilder, walking offsets and validity bitmaps instead of records.[Arrow]
On disk, a nested leaf column’s data page holds the repetition levels, then the definition levels (each with the 4-byte length in a v1 page), then the values.[README] num_values in the page header counts level entries, “including NULLs”, not rows. A v1 page may start in the middle of a row (an entry with r > 0) unless the column has an OffsetIndex; a v2 page must not: “Every page must begin at a row boundary (repetition_level = 0)”.[parquet.thrift]
Q1. A record has no Links group (it is optional). What does the shredder write?
Q2. Which statements about a nested leaf column's data page are true? (Select all.) (select all that apply)
Assembly
Reading reverses the process: from the (value, r, d) streams of the projected columns, rebuild the records. For one column the rules mirror the shredder. For each entry, walk the path from the root:
- If
r = 0, start a new record. - At a repeated field whose repetition depth is at least
r, start a new element; at a shallower one, continue the last element. - At the first field deeper than
damong the non-required fields, stop: that field is null (optional) or an empty list (repeated). - If
dreaches the leaf, store the value.
That is assembleColumn in the book’s code. Run it on Name.Url alone and you get both records with the right number of Name elements: {Name: [{Url: A}, {Url: B}, {Url: null}]} and {Name: [{Url: C}]}. Each leaf column carries the full shape of its ancestors, which is why a query can read one field of a deep struct without touching its siblings.
Dremel assembles all projected columns in one pass with a finite-state machine. There is one state per leaf column, and the transitions are labeled with repetition levels: after reading a value, the reader peeks at the next entry’s r in the same column, which says at which level the next value repeats, and so whether to read on in this column or jump back to the first column under that level. parquet-java builds the machine once per schema in RecordReaderImplementation, precomputing for each leaf and each repetition level the next column (nextColumnIdxForRepLevel) and how many groups to close (levelToClose):[parquet-java]
public T read() {
int currentLevel = 0;
recordRootConverter.start();
State currentState = states[0];
do {
ColumnReader columnReader = currentState.column;
int d = columnReader.getCurrentDefinitionLevel();
// creating needed nested groups until the current field (opening tags)
int depth = currentState.definitionLevelToDepth[d];
for (; currentLevel <= depth; ++currentLevel) {
currentState.groupConverterPath[currentLevel].start();
}
if (d >= currentState.maxDefinitionLevel) {
columnReader.writeCurrentValueToConverter();
}
columnReader.consume();
int nextR = currentState.maxRepetitionLevel == 0 ? 0 : columnReader.getCurrentRepetitionLevel();
// level to go to close current groups
int next = currentState.nextLevel[nextR];
for (; currentLevel > next; currentLevel--) {
currentState.groupConverterPath[currentLevel - 1].end();
}
currentState = currentState.nextState[nextR];
} while (currentState != null);
recordRootConverter.end();
...
}
[parquet-java] Columnar engines do not build records at all. Arrow C++ turns definition levels into validity bitmaps (DefLevelsToBitmap) and repetition plus definition levels into list offsets (DefRepLevelsToList), one Arrow array per level of nesting.[Arrow level_conversion.h] That is the per-column method again: each array is built from one leaf column’s levels. The book’s assemble does the same and then merges the per-column trees, which gives the same records as the state machine.
Spark reads nested columns with its vectorized reader (spark.sql.parquet.enableNestedColumnVectorizedReader, added in 3.3, is true by default at 4.0.1), and prunes unused struct fields before the scan (spark.sql.optimizer.nestedSchemaPruning.enabled), so SELECT customer.city reads one leaf column.[Spark SQLConf][Spark SQLConf]
Q1. Dremel's record assembly reads columns with a finite-state machine. What decides which column the machine reads next?
Q2. A query reads only Name.Url. What does the reader return for a record whose Name has three elements, the third without a Url?
LIST and MAP
The Dremel schema uses bare repeated fields. Parquet still reads those (“a required list of required elements”), but writers should annotate lists and maps with a fixed 3-level structure, and a schema should use either the annotations or bare repeated fields, not both.[LogicalTypes.md]
“LIST must always annotate a 3-level structure”:[LogicalTypes.md]
<list-repetition> group <name> (LIST) {
repeated group list {
<element-repetition> <element-type> element;
}
}
The three levels are there because a field has exactly one repetition. The outer group’s optional or required says whether the list can be null; the middle repeated group list carries the repetition; the inner element’s optional or required says whether elements can be null. With only two levels the repeated field would be the element, and there would be no way to say an element is null. A nullable list of nullable strings has max d 3, and the four cases are four different levels:
optional group tags (LIST) { repeated group list { optional binary element (STRING); } }
tags entries (value r d)
null NULL 0 0 tags not defined
[] NULL 0 1 tags defined, list empty
[null] NULL 0 2 one element, element null
["a", "b"] a 0 3, b 1 3
Older files used other shapes: a 2-level list (repeated int32 element directly under the LIST group), middle groups named array or <name>_tuple, or a list group with a different element name. LogicalTypes.md gives five backward-compatibility rules a reader applies to decide which field is the element: a repeated non-group, a repeated group with several fields, a repeated group whose one field is itself repeated, and a group named array or <name>_tuple are all the element type, with required elements; otherwise the repeated group’s single child is the element.[LogicalTypes.md]
MAP is the same idea with a key and a value:[LogicalTypes.md]
<map-repetition> group <name> (MAP) {
repeated group key_value {
required <key-type> key;
<value-repetition> <value-type> value;
}
}
key must be required and first; value may be required, optional or omitted (a set). Duplicate keys are not a multi-map: “the final value for that key must be the last value”. Older files that used MAP_KEY_VALUE on the outer group are read as MAP.
The book’s ORDERS example has a struct, a list of structs, a list of strings and a map, and is what Arrow writes for the matching Arrow schema; the tests read Arrow’s file and get the same records. Its eight leaf columns:
order_id r 0 d 0
customer.name r 0 d 1 optional struct, required field
customer.city r 0 d 2
items.list.element.sku r 1 d 3 optional list, optional struct element, required field
items.list.element.qty r 1 d 3
tags.list.element r 1 d 3
attrs.key_value.key r 1 d 2 key is required
attrs.key_value.value r 1 d 3
LogicalTypes.md at the pinned commit also defines FINITE_VECTOR(n), a LIST of exactly n required, finite numbers (for embeddings), using the same 3-level structure.[LogicalTypes.md]
Q1. What must a new writer produce for a nullable list of non-null strings?
Q2. Why does LIST need three levels rather than optional group tags (LIST) { repeated binary element; }?
Q3. Which are true of the MAP structure? (Select all.) (select all that apply)
Variant and shredding
Structs, lists and maps need a schema. Semi-structured data (JSON events whose fields differ row to row) does not have one, and storing it as a JSON string gives up both columnar reads and statistics. The VARIANT logical type stores each value in a self-describing binary encoding in a group of two binary fields:[LogicalTypes.md][VariantEncoding.md]
optional group event (VARIANT(1)) {
required binary metadata; -- header byte, then a dictionary of the field names used
required binary value; -- 1 header byte (2-bit basic type: primitive, short string, object, array) + data
}
Objects in value store field ids, which index the field-name dictionary in metadata, and every nested value is contiguous and self-contained, so an engine can find $.a.b by following offsets without parsing the rest.
Shredding pulls frequently used parts of the Variant into ordinary typed Parquet columns, next to the binary value. Each value may get a sibling typed_value; value becomes optional, and the two together encode one value:[VariantShredding.md]
value | typed_value | Meaning |
|---|---|---|
| null | null | missing (only valid for a shredded object field) |
| non-null | null | present, any type, stored in the binary encoding |
| null | non-null | present, and of the shredded type |
| non-null | non-null | a partially shredded object |
A Variant shredded as optional int64 typed_value stores 34, null, "n/a", 100 as typed 34, value 00 (the one-byte Variant null), value "n/a" (it is not an int64), typed 100. Objects shred into a typed_value group with one required group per shredded field, each with its own value and typed_value; fields that are not shredded stay in the object’s value, and “the value column of a partially shredded object must never contain fields represented by the Parquet columns in typed_value”.[VariantShredding.md]
optional group event (VARIANT(1)) {
required binary metadata;
optional binary value; -- the rest of the object
optional group typed_value {
required group event_type { optional binary value; optional binary typed_value (STRING); }
required group event_ts { optional binary value; optional int64 typed_value (TIMESTAMP(true, MICROS)); }
}
}
Now variant_get(event, '$.event_ts', 'timestamp') reads one INT64 leaf column, and that column has min/max statistics. The statistics are only safe to skip with when the matching value column is all null in that file, row group or page; otherwise some rows hold an event_ts of another type that the statistics do not describe.[VariantShredding.md] All the machinery of this chapter applies unchanged: shredded Variant columns are ordinary nested leaf columns with repetition and definition levels.
Q1. An unshredded VARIANT column is stored as which Parquet structure?
Q2. A Variant column shredded with optional int64 typed_value stores the series 34, null, "n/a". Which row has both value and typed_value null?
Q3. When can a reader use the min/max statistics of a shredded typed_value column to skip data?
Try it
The explorer shreds the records in the text box with the book’s shredder, shows every leaf column’s (value, r, d) entries, and assembles records from the columns you tick.
- With Dremel paper: Document, compare the columns with figure 3 above. Click record 0 to highlight its entries in every column; a heavy rule marks each r 0.
- Delete
,"Country":"us"from the first Language and watchName.Language.Countrychange fromus 0 3toNULL 0 2. - Untick everything except
Name.Url: the assembled records still have three Names in record 0. - Switch to LIST: null, empty, [null], [a, b] and read the d column: 0, 1, 2, 3, 3.
- Switch to Orders and add an attribute to an order. The
attrs.key_value.keyandattrs.key_value.valuecolumns gain an entry with r 1.
Schema
message Document {
required int64 DocId;
optional group Links {
repeated int64 Backward;
repeated int64 Forward;
}
repeated group Name {
repeated group Language {
required binary Code (STRING);
optional binary Country (STRING);
}
optional binary Url (STRING);
}
}Records · JSON, editable
Leaf columns · value, repetition level r, definition level d
DocIdmax r 0 · max d 0| value | r | d |
|---|---|---|
| 10 | 0 | 0 |
| 20 | 0 | 0 |
Links.Backwardmax r 1 · max d 2| value | r | d |
|---|---|---|
| NULL | 0 | 1 |
| 10 | 0 | 2 |
| 30 | 1 | 2 |
Links.Forwardmax r 1 · max d 2| value | r | d |
|---|---|---|
| 20 | 0 | 2 |
| 40 | 1 | 2 |
| 60 | 1 | 2 |
| 80 | 0 | 2 |
Name.Language.Codemax r 2 · max d 2| value | r | d |
|---|---|---|
| "en-us" | 0 | 2 |
| "en" | 2 | 2 |
| NULL | 1 | 1 |
| "en-gb" | 1 | 2 |
| NULL | 0 | 1 |
Name.Language.Countrymax r 2 · max d 3| value | r | d |
|---|---|---|
| "us" | 0 | 3 |
| NULL | 2 | 2 |
| NULL | 1 | 1 |
| "gb" | 1 | 3 |
| NULL | 0 | 1 |
Name.Urlmax r 1 · max d 2| value | r | d |
|---|---|---|
| "http://A" | 0 | 2 |
| "http://B" | 1 | 2 |
| NULL | 1 | 1 |
| "http://C" | 0 | 2 |
Assemble from these columns only
{"Name":[{"Url":"http://A"},{"Url":"http://B"},{"Url":null}]}
{"Name":[{"Url":"http://C"}]}A projection: the physical shape, with the LIST and MAP groups visible. Written as a Parquet file: 764 bytes.
Summary
- Each leaf column stores (r, d, value) entries. Max r is the number of repeated fields on the path; max d the number of non-required fields. Only
d = maxentries have a value. r = 0starts a record;r = kstarts a new element of the k-th repeated field. A missing optional field or empty list writes one NULL entry into every leaf below it, at the parent’s d.- Each leaf column alone carries the shape of its ancestors, so a reader can project one nested field. parquet-java assembles records with Dremel’s state machine; Arrow converts levels to validity bitmaps and list offsets.
- LIST and MAP must use the 3-level structure, because element and value nullability needs its own field. Readers still accept older 2-level lists by five rules.
- Variant stores semi-structured values as binary
metadataandvalue; shredding adds typed columns that can be projected and, whenvalueis all null, skipped by statistics.
Spec links point to apache/parquet-format at 6f87925. Implementation links point to parquet-java 1.17.1, Arrow C++ 26.0.0 and Spark 4.0.1.
Concepts in this chapter
Explained here
Primary sources
Review this chapter
This chapter has 14 quiz questions.