You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by GitBox <gi...@apache.org> on 2022/05/11 07:43:25 UTC

[GitHub] [arrow-rs] tustvold commented on a diff in pull request #1682: Fix Parquet Arrow Schema Inference

tustvold commented on code in PR #1682:
URL: https://github.com/apache/arrow-rs/pull/1682#discussion_r869953255


##########
parquet/src/arrow/schema.rs:
##########
@@ -544,502 +525,6 @@ fn arrow_to_parquet_type(field: &Field) -> Result<Type> {
         }
     }
 }
-/// This struct is used to group methods and data structures used to convert parquet
-/// schema together.
-struct ParquetTypeConverter<'a> {
-    schema: &'a Type,
-    /// This is the columns that need to be converted to arrow schema.
-    columns_to_convert: &'a HashSet<*const Type>,
-}
-
-impl<'a> ParquetTypeConverter<'a> {
-    fn new(schema: &'a Type, columns_to_convert: &'a HashSet<*const Type>) -> Self {
-        Self {
-            schema,
-            columns_to_convert,
-        }
-    }
-
-    fn clone_with_schema(&self, other: &'a Type) -> Self {
-        Self {
-            schema: other,
-            columns_to_convert: self.columns_to_convert,
-        }
-    }
-}
-
-impl ParquetTypeConverter<'_> {

Review Comment:
   This logic is copied largely wholesale into schema/primitive.rs



##########
parquet/src/arrow/schema/complex.rs:
##########
@@ -0,0 +1,563 @@
+// 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.
+
+use crate::arrow::schema::primitive::convert_primitive;
+use crate::basic::{ConvertedType, Repetition};
+use crate::errors::ParquetError;
+use crate::errors::Result;
+use crate::schema::types::{SchemaDescriptor, Type, TypePtr};
+use arrow::datatypes::{DataType, Field, Schema};
+
+fn get_repetition(t: &Type) -> Repetition {
+    let info = t.get_basic_info();
+    match info.has_repetition() {
+        true => info.repetition(),
+        false => Repetition::REQUIRED,
+    }
+}
+
+/// Representation of a parquet file, in terms of arrow schema elements
+pub struct ParquetField {
+    pub rep_level: i16,
+    pub def_level: i16,
+    pub nullable: bool,
+    pub arrow_type: DataType,
+    pub field_type: ParquetFieldType,
+}
+
+impl ParquetField {
+    fn into_list(self, name: &str) -> Self {
+        ParquetField {
+            rep_level: self.rep_level,
+            def_level: self.def_level,
+            nullable: false,
+            arrow_type: DataType::List(Box::new(Field::new(
+                name,
+                self.arrow_type.clone(),
+                false,
+            ))),
+            field_type: ParquetFieldType::Group {
+                children: vec![self],
+            },
+        }
+    }
+
+    pub fn children(&self) -> Option<&[ParquetField]> {
+        match &self.field_type {
+            ParquetFieldType::Primitive { .. } => None,
+            ParquetFieldType::Group { children } => Some(children),
+        }
+    }
+}
+
+pub enum ParquetFieldType {
+    Primitive {
+        col_idx: usize,
+        primitive_type: TypePtr,
+    },
+    Group {
+        children: Vec<ParquetField>,
+    },
+}
+
+struct VisitorContext {
+    rep_level: i16,
+    def_level: i16,
+    /// An optional [`DataType`] sourced from the embedded arrow schema
+    data_type: Option<DataType>,
+}
+
+impl VisitorContext {
+    fn levels(&self, repetition: Repetition) -> (i16, i16, bool) {
+        match repetition {
+            Repetition::OPTIONAL => (self.def_level + 1, self.rep_level, true),
+            Repetition::REQUIRED => (self.def_level, self.rep_level, false),
+            Repetition::REPEATED => (self.def_level + 1, self.rep_level + 1, false),
+        }
+    }
+}
+
+/// Walks the parquet schema in a depth-first fashion in order to extract the
+/// necessary information to map it to arrow data structures
+///
+/// See [Logical Types] for more information on the conversion algorithm
+///
+/// [Logical Types]: https://github.com/apache/parquet-format/blob/master/LogicalTypes.md
+struct Visitor {
+    /// The column index of the next leaf column
+    next_col_idx: usize,
+
+    /// Mask of columns to include
+    column_mask: Vec<bool>,
+}
+
+impl Visitor {
+    fn visit_primitive(
+        &mut self,
+        primitive_type: TypePtr,
+        context: VisitorContext,
+    ) -> Result<Option<ParquetField>> {
+        let col_idx = self.next_col_idx;
+        self.next_col_idx += 1;
+
+        if !self.column_mask[col_idx] {
+            return Ok(None);
+        }
+
+        let repetition = get_repetition(&primitive_type);
+        let (def_level, rep_level, nullable) = context.levels(repetition);
+
+        let arrow_type = convert_primitive(&primitive_type, context.data_type)?;
+
+        let primitive_field = ParquetField {
+            rep_level,
+            def_level,
+            nullable,
+            arrow_type,
+            field_type: ParquetFieldType::Primitive {
+                primitive_type: primitive_type.clone(),
+                col_idx,
+            },
+        };
+
+        Ok(Some(match repetition {
+            Repetition::REPEATED => primitive_field.into_list(primitive_type.name()),

Review Comment:
   Here is the logic to now support #1680, there is comprehensive test coverage of this in schema.rs, in particular test_arrow_schema_roundtrip



##########
parquet/src/arrow/schema.rs:
##########
@@ -1261,7 +746,7 @@ mod tests {
         {
             arrow_fields.push(Field::new(
                 "my_list",
-                DataType::List(Box::new(Field::new("element", DataType::Utf8, true))),
+                DataType::List(Box::new(Field::new("str", DataType::Utf8, false))),

Review Comment:
   Here we can see this fixing #1681 



##########
parquet/src/arrow/schema.rs:
##########
@@ -1679,7 +1168,7 @@ mod tests {
 
         let parquet_schema = SchemaDescriptor::new(Arc::new(parquet_group_type));
         let converted_arrow_schema =
-            parquet_to_arrow_schema_by_columns(&parquet_schema, vec![3, 4, 0], None)
+            parquet_to_arrow_schema_by_columns(&parquet_schema, vec![0, 3, 4], None)

Review Comment:
   Out of order column projection previously would misbehave as `parquet_to_arrow_schema_by_columns` supported it, but the actual reader logic did not. This makes it consistently not supported, it will error, as it is hard to reason what the correct semantics are in the event of nested schema



##########
parquet/src/arrow/schema/complex.rs:
##########
@@ -0,0 +1,563 @@
+// 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.
+
+use crate::arrow::schema::primitive::convert_primitive;
+use crate::basic::{ConvertedType, Repetition};
+use crate::errors::ParquetError;
+use crate::errors::Result;
+use crate::schema::types::{SchemaDescriptor, Type, TypePtr};
+use arrow::datatypes::{DataType, Field, Schema};
+
+fn get_repetition(t: &Type) -> Repetition {
+    let info = t.get_basic_info();
+    match info.has_repetition() {
+        true => info.repetition(),
+        false => Repetition::REQUIRED,
+    }
+}
+
+/// Representation of a parquet file, in terms of arrow schema elements
+pub struct ParquetField {
+    pub rep_level: i16,
+    pub def_level: i16,
+    pub nullable: bool,
+    pub arrow_type: DataType,
+    pub field_type: ParquetFieldType,
+}
+
+impl ParquetField {
+    fn into_list(self, name: &str) -> Self {
+        ParquetField {
+            rep_level: self.rep_level,
+            def_level: self.def_level,
+            nullable: false,
+            arrow_type: DataType::List(Box::new(Field::new(
+                name,
+                self.arrow_type.clone(),
+                false,
+            ))),
+            field_type: ParquetFieldType::Group {
+                children: vec![self],
+            },
+        }
+    }
+
+    pub fn children(&self) -> Option<&[ParquetField]> {
+        match &self.field_type {
+            ParquetFieldType::Primitive { .. } => None,
+            ParquetFieldType::Group { children } => Some(children),
+        }
+    }
+}
+
+pub enum ParquetFieldType {
+    Primitive {
+        col_idx: usize,
+        primitive_type: TypePtr,
+    },
+    Group {
+        children: Vec<ParquetField>,
+    },
+}
+
+struct VisitorContext {
+    rep_level: i16,
+    def_level: i16,
+    /// An optional [`DataType`] sourced from the embedded arrow schema
+    data_type: Option<DataType>,
+}
+
+impl VisitorContext {
+    fn levels(&self, repetition: Repetition) -> (i16, i16, bool) {
+        match repetition {
+            Repetition::OPTIONAL => (self.def_level + 1, self.rep_level, true),
+            Repetition::REQUIRED => (self.def_level, self.rep_level, false),
+            Repetition::REPEATED => (self.def_level + 1, self.rep_level + 1, false),
+        }
+    }
+}
+
+/// Walks the parquet schema in a depth-first fashion in order to extract the
+/// necessary information to map it to arrow data structures
+///
+/// See [Logical Types] for more information on the conversion algorithm
+///
+/// [Logical Types]: https://github.com/apache/parquet-format/blob/master/LogicalTypes.md
+struct Visitor {
+    /// The column index of the next leaf column
+    next_col_idx: usize,
+
+    /// Mask of columns to include
+    column_mask: Vec<bool>,
+}
+
+impl Visitor {

Review Comment:
   This is logic extracted from builder.rs, it wasn't possible to reuse the existing TypeVisitor as its handling of lists interfered with #1680



##########
parquet/src/arrow/schema/complex.rs:
##########
@@ -0,0 +1,563 @@
+// 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.
+
+use crate::arrow::schema::primitive::convert_primitive;
+use crate::basic::{ConvertedType, Repetition};
+use crate::errors::ParquetError;
+use crate::errors::Result;
+use crate::schema::types::{SchemaDescriptor, Type, TypePtr};
+use arrow::datatypes::{DataType, Field, Schema};
+
+fn get_repetition(t: &Type) -> Repetition {
+    let info = t.get_basic_info();
+    match info.has_repetition() {
+        true => info.repetition(),
+        false => Repetition::REQUIRED,
+    }
+}
+
+/// Representation of a parquet file, in terms of arrow schema elements
+pub struct ParquetField {

Review Comment:
   This is the new structure as described in #1655 



##########
parquet/src/arrow/schema/primitive.rs:
##########
@@ -0,0 +1,266 @@
+// 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.
+
+use crate::basic::{
+    ConvertedType, LogicalType, TimeUnit as ParquetTimeUnit, Type as PhysicalType,
+};
+use crate::errors::{ParquetError, Result};
+use crate::schema::types::{BasicTypeInfo, Type};
+use arrow::datatypes::{DataType, IntervalUnit, TimeUnit};
+
+/// Converts [`Type`] to [`DataType`] with an optional `arrow_type_hint`
+/// provided by the arrow schema
+///
+/// Note: the values embedded in the schema are advisory,
+pub fn convert_primitive(
+    parquet_type: &Type,
+    arrow_type_hint: Option<DataType>,
+) -> Result<DataType> {
+    let physical_type = from_parquet(parquet_type)?;
+    Ok(match arrow_type_hint {
+        Some(hint) => apply_hint(physical_type, hint),
+        None => physical_type,
+    })
+}
+
+/// Uses an type hint from the embedded arrow schema to aid in faithfully
+/// reproducing the data as it was written into parquet
+fn apply_hint(parquet: DataType, hint: DataType) -> DataType {

Review Comment:
   This is the change that fixes #1663 - we only use the arrow schema to hint types



##########
parquet/src/arrow/schema/complex.rs:
##########
@@ -0,0 +1,563 @@
+// 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.
+
+use crate::arrow::schema::primitive::convert_primitive;
+use crate::basic::{ConvertedType, Repetition};
+use crate::errors::ParquetError;
+use crate::errors::Result;
+use crate::schema::types::{SchemaDescriptor, Type, TypePtr};
+use arrow::datatypes::{DataType, Field, Schema};
+
+fn get_repetition(t: &Type) -> Repetition {
+    let info = t.get_basic_info();
+    match info.has_repetition() {
+        true => info.repetition(),
+        false => Repetition::REQUIRED,
+    }
+}
+
+/// Representation of a parquet file, in terms of arrow schema elements
+pub struct ParquetField {
+    pub rep_level: i16,
+    pub def_level: i16,
+    pub nullable: bool,
+    pub arrow_type: DataType,
+    pub field_type: ParquetFieldType,
+}
+
+impl ParquetField {
+    fn into_list(self, name: &str) -> Self {
+        ParquetField {
+            rep_level: self.rep_level,
+            def_level: self.def_level,
+            nullable: false,
+            arrow_type: DataType::List(Box::new(Field::new(
+                name,
+                self.arrow_type.clone(),
+                false,
+            ))),
+            field_type: ParquetFieldType::Group {
+                children: vec![self],
+            },
+        }
+    }
+
+    pub fn children(&self) -> Option<&[ParquetField]> {
+        match &self.field_type {
+            ParquetFieldType::Primitive { .. } => None,
+            ParquetFieldType::Group { children } => Some(children),
+        }
+    }
+}
+
+pub enum ParquetFieldType {
+    Primitive {
+        col_idx: usize,
+        primitive_type: TypePtr,
+    },
+    Group {
+        children: Vec<ParquetField>,
+    },
+}
+
+struct VisitorContext {
+    rep_level: i16,
+    def_level: i16,
+    /// An optional [`DataType`] sourced from the embedded arrow schema
+    data_type: Option<DataType>,

Review Comment:
   This is what fixes #1654 - we carry the DataType as we walk the tree, which prevents it from misbehaving



##########
parquet/src/arrow/arrow_reader.rs:
##########
@@ -1050,6 +1050,41 @@ mod tests {
         for batch in record_batch_reader {
             batch.unwrap();
         }
+
+        let projected_reader = arrow_reader

Review Comment:
   This is a test for #1654 and #1652



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org