tustvold commented on code in PR #247:
URL: https://github.com/apache/arrow-site/pull/247#discussion_r996198068


##########
_posts/2022-10-01-arrow-parquet-encoding-part-3.md:
##########
@@ -0,0 +1,169 @@
+---
+layout: post
+title: "Arrow and Parquet Part 3: Arbitrary Nesting with Lists of Structs and 
Structs of Lists"
+date: "2022-10-01 00:00:00"
+author: "tustvold and alamb"
+categories: [parquet, arrow]
+---
+<!--
+{% comment %}
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements.  See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to you under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License.  You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+{% endcomment %}
+-->
+
+## Introduction
+
+This is the third of a three part series exploring how projects such as [Rust 
Apache Arrow](https://github.com/apache/arrow-rs) support conversion between 
[Apache Arrow](https://arrow.apache.org/) for in memory processing and [Apache 
Parquet](https://parquet.apache.org/) for efficient storage. This post covers 
how to combine the `Struct` and `List` types described in the previous posts 
for arbitrary nesting.
+
+
+[Apache Arrow](https://arrow.apache.org/) is an open, language-independent 
columnar memory format for flat and hierarchical data, organized for efficient 
analytic operations. [Apache Parquet](https://parquet.apache.org/) is an open, 
column-oriented data file format designed for very efficient data encoding and 
retrieval.
+
+
+# Structs with Lists
+
+
+```json
+{                     <-- First record
+  “a”: [1],           <-- top-level field a containing list of integers
+  “b”: [              <-- top-level field b containing list of structures
+    {                 <-- list element of b containing two field b1 and b2
+      “b1”: 1         <-- b1 is always provided (not null)
+    },
+    {
+      “b1”: 1,
+      “b2”: [         <-- b2 contains list of integers
+        3, 4          <-- list elements of b.b2 always provided (not null)
+      ]
+    }
+  ]
+}
+{
+  “b”: [              <-- b is always provided (not null)
+    {
+      “b1”: 2
+    },
+  ]
+}
+{
+  “a”: [null, null],  <-- list elements of a are nullable
+  “b”: [null]         <-- list elements of b are nullable
+}
+```
+
+Documents of this format could be stored in this arrow schema
+
+```text
+Field(name: “a”, nullable: true, datatype: List(
+  Field(name: “element”, nullable: true, datatype: Int32),
+)
+Field(name: “b”), nullable: false, datatype: List(
+  Field(name: “element”, nullable: true, datatype: Struct[
+    Field(name: “b1”, nullable: false, datatype: Int32),
+    Field(name: “b2”, nullable: true, datatype: List(
+      Field(name: “element”, nullable: false, datatype: Int32)
+    ))
+  ])
+))
+```
+
+Documents of this format could be stored in this parquet schema
+
+```text
+message schema {
+  optional group a (LIST) {
+    repeated group list {
+      optional int32 element;
+    }
+  }
+  required group b (LIST) {
+    repeated group list {
+      optional group element {
+        required int32 b1;
+        optional group b2 (LIST) {
+          repeated group list {
+            required int32 element;
+          }
+        }
+      }
+    }
+  }
+}
+```
+
+As explained previously, Arrow chooses to represent this in a hierarchical 
fashion. To achieve this it stores a list of monotonically increasing integers 
called offsets in the parent ListArray, and stores all the values that appear 
in the lists in a single child array. Each consecutive pair of elements in this 
offset array identifies a slice of the child array for that array index.
+
+```text
+a: ListArray
+  Offsets: [0, 1, 1, 3]
+  Validity: [true, false, true]
+  Children:
+    element: PrimitiveArray
+      Buffer[0]: [1, ARBITRARY, ARBITRARY]
+      Validity: [true, false, false]
+b: ListArray
+  Offsets: [0, 2, 3, 4]
+  Children:
+    element: StructArray
+      Validity: [true, true, true, false]
+      Children:
+        b1: PrimitiveArray
+          Buffer[0]: [1, 1, 2, ARBITRARY]
+        b2: ListArray
+          Offsets: [0, 0, 2, 2, 2]
+          Validity: [false, true, false, ARBITRARY]
+          Children:
+            element: PrimitiveArray
+              Buffer[0]: [3, 4]
+```
+
+In order to encode lists, Parquet stores an integer repetition level in 
addition to a definition level. A repetition level identifies where in the 
hierarchy of repeated fields the current value is to be inserted. A value of 0 
would imply a new list in the top-most repeated field, a value of 1 a new 
element within the top-most repeated field, a value of 2 a new element within 
the second top-most repeated field, and so on.
+
+Each repeated field also has a corresponding definition level, however, in 
this case rather than indicating a null value, they indicate an empty array.
+
+```text

Review Comment:
   Verified with
   
   ```
   #[test]
       fn test_foo() {
           let mut a = ListBuilder::new(Int32Builder::new());
           a.values().append_value(1);
           a.append(true);
           a.append(false);
           a.values().append_null();
           a.values().append_null();
           a.append(true);
           let values = Arc::new(a.finish()) as ArrayRef;
   
           let mut builder = LevelInfoBuilder::try_new(
               &Field::new("test", values.data_type().clone(), true),
               Default::default(),
           )
           .unwrap();
           builder.write(&values, 0..3);
           let levels = builder.finish();
   
           assert_eq!(levels.len(), 1);
   
           let list_level = levels.get(0).unwrap();
   
           let expected_level = LevelInfo {
               def_levels: Some(vec![3, 0, 2, 2]),
               rep_levels: Some(vec![0, 0, 0, 1]),
               non_null_indices: vec![0],
               max_def_level: 3,
               max_rep_level: 1,
           };
           assert_eq!(list_level, &expected_level);
   
           let b2 = DataType::List(Box::new(Field::new("element", 
DataType::Int32, false)));
           let s = StructBuilder::new(
               vec![
                   Field::new("b1", DataType::Int32, false),
                   Field::new("b2", b2, true),
               ],
               vec![
                   Box::new(Int32Builder::new()),
                   Box::new(ListBuilder::new(Int32Builder::new())),
               ],
           );
   
           let mut b = ListBuilder::new(s);
           b.values()
               .field_builder::<Int32Builder>(0)
               .unwrap()
               .append_value(1);
           b.values()
               .field_builder::<ListBuilder<Int32Builder>>(1)
               .unwrap()
               .append(false);
           b.values().append(true);
           b.values()
               .field_builder::<Int32Builder>(0)
               .unwrap()
               .append_value(1);
           b.values()
               .field_builder::<ListBuilder<Int32Builder>>(1)
               .unwrap()
               .values()
               .append_value(3);
           b.values()
               .field_builder::<ListBuilder<Int32Builder>>(1)
               .unwrap()
               .values()
               .append_value(4);
           b.values()
               .field_builder::<ListBuilder<Int32Builder>>(1)
               .unwrap()
               .append(true);
           b.values().append(true);
           b.append(true);
           b.values()
               .field_builder::<Int32Builder>(0)
               .unwrap()
               .append_value(2);
           b.values()
               .field_builder::<ListBuilder<Int32Builder>>(1)
               .unwrap()
               .append(false);
           b.values().append(true);
           b.append(true);
           b.values()
               .field_builder::<Int32Builder>(0)
               .unwrap()
               .append_value(0);
           b.values()
               .field_builder::<ListBuilder<Int32Builder>>(1)
               .unwrap()
               .append(false);
           b.values().append_null();
           b.append(true);
   
           let values = Arc::new(b.finish()) as ArrayRef;
   
           let mut builder = LevelInfoBuilder::try_new(
               &Field::new("test", values.data_type().clone(), false),
               Default::default(),
           )
           .unwrap();
           builder.write(&values, 0..3);
           let levels = builder.finish();
   
           assert_eq!(levels.len(), 2);
   
           let list_level = levels.get(0).unwrap();
   
           let expected_level = LevelInfo {
               def_levels: Some(vec![2, 2, 2, 1]),
               rep_levels: Some(vec![0, 1, 0, 0]),
               non_null_indices: vec![0, 1, 2],
               max_def_level: 2,
               max_rep_level: 1,
           };
           assert_eq!(list_level, &expected_level);
   
           let list_level = levels.get(1).unwrap();
   
           let expected_level = LevelInfo {
               def_levels: Some(vec![2, 4, 4, 2, 1]),
               rep_levels: Some(vec![0, 1, 2, 0, 0]),
               non_null_indices: vec![0, 1],
               max_def_level: 4,
               max_rep_level: 2,
           };
           assert_eq!(list_level, &expected_level);
       }
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to