You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by GitBox <gi...@apache.org> on 2021/07/28 12:35:16 UTC

[GitHub] [iceberg] TGooch44 opened a new pull request #2884: [python] Adding utility functions for converting iceberg to arrow

TGooch44 opened a new pull request #2884:
URL: https://github.com/apache/iceberg/pull/2884


   Utility functions for creating an arrow schema from an iceberg schema.  This will be necessary for an eventual write path.


-- 
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: issues-unsubscribe@iceberg.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] TGooch44 closed pull request #2884: [python] Adding utility functions for converting iceberg to arrow

Posted by GitBox <gi...@apache.org>.
TGooch44 closed pull request #2884:
URL: https://github.com/apache/iceberg/pull/2884


   


-- 
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: issues-unsubscribe@iceberg.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kainoa21 commented on a change in pull request #2884: [python] Adding utility functions for converting iceberg to arrow

Posted by GitBox <gi...@apache.org>.
kainoa21 commented on a change in pull request #2884:
URL: https://github.com/apache/iceberg/pull/2884#discussion_r689941615



##########
File path: python/iceberg/parquet/iceberg_to_arrow.py
##########
@@ -0,0 +1,107 @@
+# 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.
+
+
+import json
+from typing import Callable, Dict
+
+from iceberg.api import Schema
+from iceberg.api.types import NestedField, TypeID
+from iceberg.core import SchemaParser
+import pyarrow as pa
+
+
+ICEBERG_TO_ARROW_MAP: Dict[TypeID, Callable] = {
+    TypeID.BOOLEAN: lambda type_var: pa.lib.bool_(),
+    TypeID.BINARY: lambda type_var: pa.lib.binary(),
+    TypeID.DATE: lambda type_var: pa.lib.date32(),
+    TypeID.DECIMAL: lambda type_var: pa.lib.decimal128(type_var.precision, type_var.scale),
+    TypeID.DOUBLE: lambda type_var: pa.lib.float64(),
+    TypeID.FIXED: lambda type_var: pa.lib.binary(length=type_var.length),
+    TypeID.FLOAT: lambda type_var: pa.lib.float32(),
+    TypeID.INTEGER: lambda type_var: pa.lib.int32(),
+    TypeID.LIST: lambda type_var: convert_field(type_var),
+    TypeID.LONG: lambda type_var: pa.lib.int64(),
+    TypeID.MAP: lambda type_var: convert_field(type_var),
+    TypeID.STRING: lambda type_var: pa.lib.string(),
+    TypeID.STRUCT: lambda type_var: convert_field(type_var),
+    TypeID.TIME: lambda type_var: pa.lib.time64("us"),
+    TypeID.TIMESTAMP: lambda type_var: pa.timestamp("us", tz="UTC" if type_var.adjust_to_utc else None),
+}
+
+
+def iceberg_to_arrow(iceberg_schema: Schema) -> pa.Schema:
+    """
+    Use an iceberg schema, to create an equivalent arrow schema with intact field_id metadata
+
+    Parameters
+    ----------
+    iceberg_schema : Schema
+        An iceberg schema to map
+
+    Returns
+    -------
+    pyarrow.Schema
+        returns an equivalent pyarrow Schema based on the iceberg schema provided. Performs
+    """
+    arrow_fields = []
+    for field in iceberg_schema.as_struct().fields:
+        arrow_fields.append(convert_field(field))
+
+    return pa.schema(arrow_fields,
+                     metadata={b'iceberg.schema': json.dumps(SchemaParser.to_dict(iceberg_schema)).encode("utf-8")})
+
+
+def convert_field(iceberg_field: NestedField) -> pa.Field:
+    """
+        Map an iceberg field to a pyarrow field. Recursively calls itself for nested fields
+        there is currently a limitation in the ability to convert map types since the pyarrow python bindings
+        don't expose a way to set fields for the key and value fields in a map
+
+        Parameters
+        ----------
+        iceberg_field: NestedField
+            An iceberg schema to map
+
+        Returns
+        -------
+        pa.Field
+            returns an equivalent pyarow Field based on the Nested Field.
+        """
+    if iceberg_field.type.is_primitive_type():
+        try:
+            arrow_field = ICEBERG_TO_ARROW_MAP[iceberg_field.type.type_id](iceberg_field.type)
+        except KeyError:
+            raise ValueError(f"Unable to convert {iceberg_field}")
+
+    elif iceberg_field.type.type_id == TypeID.STRUCT:
+        arrow_field = pa.struct([convert_field(field) for field in iceberg_field.type.fields])
+    elif iceberg_field.type.type_id == TypeID.LIST:
+        try:
+            arrow_field = pa.list_(ICEBERG_TO_ARROW_MAP[iceberg_field.type.type_id](iceberg_field.type.element_field))
+        except KeyError:
+            raise ValueError(f"Unable to convert {iceberg_field.type}")
+    elif iceberg_field.type.type_id == TypeID.MAP:
+        raise NotImplementedError("Unable to serialize Map types; python arrow bindings can't pass key/val metadata")

Review comment:
       The Arrow Java implementation explicitly represents Maps as a list of structs types where the struct type has two fields (key, value).  In ArrowSchemaUtil, we leverage this and [create a MapType field](https://github.com/apache/iceberg/blob/master/arrow/src/main/java/org/apache/iceberg/arrow/ArrowSchemaUtil.java#L133) with a list of two fields (the key and value fields) as the children.  
   
   The cpp implementation seems to have an [api](https://arrow.apache.org/docs/cpp/api/datatype.html#_CPPv43mapNSt10shared_ptrI8DataTypeEENSt10shared_ptrI5FieldEEb) that allows the value part of the map to be specified as a field (instead of just a DataType).  I can't see any reason why it wouldn't be possible to have an option to create a map from fields.
   
   In the interim, is it viable to encode an iceberg map as a list of structs (similar to the Java api)?  We could even include something in the top level list field metadata indicating that it is intended to be an iceberg map type?




-- 
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: issues-unsubscribe@iceberg.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] jun-he commented on a change in pull request #2884: [python] Adding utility functions for converting iceberg to arrow

Posted by GitBox <gi...@apache.org>.
jun-he commented on a change in pull request #2884:
URL: https://github.com/apache/iceberg/pull/2884#discussion_r678612384



##########
File path: python/iceberg/parquet/iceberg_to_arrow.py
##########
@@ -0,0 +1,107 @@
+# 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.
+
+
+import json
+from typing import Callable, Dict
+
+from iceberg.api import Schema
+from iceberg.api.types import NestedField, TypeID
+from iceberg.core import SchemaParser
+import pyarrow as pa
+
+
+ICEBERG_TO_ARROW_MAP: Dict[TypeID, Callable] = {
+    TypeID.BOOLEAN: lambda type_var: pa.lib.bool_(),
+    TypeID.BINARY: lambda type_var: pa.lib.binary(),
+    TypeID.DATE: lambda type_var: pa.lib.date32(),
+    TypeID.DECIMAL: lambda type_var: pa.lib.decimal128(type_var.precision, type_var.scale),
+    TypeID.DOUBLE: lambda type_var: pa.lib.float64(),
+    TypeID.FIXED: lambda type_var: pa.lib.binary(length=type_var.length),

Review comment:
       by checking `ArrowSchemaUtil`, it seems not enforcing the length limit

##########
File path: python/iceberg/parquet/iceberg_to_arrow.py
##########
@@ -0,0 +1,107 @@
+# 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.
+
+
+import json
+from typing import Callable, Dict
+
+from iceberg.api import Schema
+from iceberg.api.types import NestedField, TypeID
+from iceberg.core import SchemaParser
+import pyarrow as pa
+
+
+ICEBERG_TO_ARROW_MAP: Dict[TypeID, Callable] = {
+    TypeID.BOOLEAN: lambda type_var: pa.lib.bool_(),
+    TypeID.BINARY: lambda type_var: pa.lib.binary(),
+    TypeID.DATE: lambda type_var: pa.lib.date32(),
+    TypeID.DECIMAL: lambda type_var: pa.lib.decimal128(type_var.precision, type_var.scale),
+    TypeID.DOUBLE: lambda type_var: pa.lib.float64(),
+    TypeID.FIXED: lambda type_var: pa.lib.binary(length=type_var.length),
+    TypeID.FLOAT: lambda type_var: pa.lib.float32(),
+    TypeID.INTEGER: lambda type_var: pa.lib.int32(),
+    TypeID.LIST: lambda type_var: convert_field(type_var),
+    TypeID.LONG: lambda type_var: pa.lib.int64(),
+    TypeID.MAP: lambda type_var: convert_field(type_var),
+    TypeID.STRING: lambda type_var: pa.lib.string(),
+    TypeID.STRUCT: lambda type_var: convert_field(type_var),
+    TypeID.TIME: lambda type_var: pa.lib.time64("us"),

Review comment:
       nit: unit ms

##########
File path: python/iceberg/parquet/iceberg_to_arrow.py
##########
@@ -0,0 +1,107 @@
+# 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.
+
+
+import json
+from typing import Callable, Dict
+
+from iceberg.api import Schema
+from iceberg.api.types import NestedField, TypeID
+from iceberg.core import SchemaParser
+import pyarrow as pa
+
+
+ICEBERG_TO_ARROW_MAP: Dict[TypeID, Callable] = {
+    TypeID.BOOLEAN: lambda type_var: pa.lib.bool_(),
+    TypeID.BINARY: lambda type_var: pa.lib.binary(),
+    TypeID.DATE: lambda type_var: pa.lib.date32(),
+    TypeID.DECIMAL: lambda type_var: pa.lib.decimal128(type_var.precision, type_var.scale),
+    TypeID.DOUBLE: lambda type_var: pa.lib.float64(),
+    TypeID.FIXED: lambda type_var: pa.lib.binary(length=type_var.length),
+    TypeID.FLOAT: lambda type_var: pa.lib.float32(),
+    TypeID.INTEGER: lambda type_var: pa.lib.int32(),
+    TypeID.LIST: lambda type_var: convert_field(type_var),
+    TypeID.LONG: lambda type_var: pa.lib.int64(),
+    TypeID.MAP: lambda type_var: convert_field(type_var),
+    TypeID.STRING: lambda type_var: pa.lib.string(),
+    TypeID.STRUCT: lambda type_var: convert_field(type_var),
+    TypeID.TIME: lambda type_var: pa.lib.time64("us"),
+    TypeID.TIMESTAMP: lambda type_var: pa.timestamp("us", tz="UTC" if type_var.adjust_to_utc else None),
+}

Review comment:
       seems missing TypeID.UUID

##########
File path: python/iceberg/parquet/iceberg_to_arrow.py
##########
@@ -0,0 +1,107 @@
+# 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.
+
+
+import json
+from typing import Callable, Dict
+
+from iceberg.api import Schema
+from iceberg.api.types import NestedField, TypeID
+from iceberg.core import SchemaParser
+import pyarrow as pa
+
+
+ICEBERG_TO_ARROW_MAP: Dict[TypeID, Callable] = {
+    TypeID.BOOLEAN: lambda type_var: pa.lib.bool_(),
+    TypeID.BINARY: lambda type_var: pa.lib.binary(),
+    TypeID.DATE: lambda type_var: pa.lib.date32(),
+    TypeID.DECIMAL: lambda type_var: pa.lib.decimal128(type_var.precision, type_var.scale),
+    TypeID.DOUBLE: lambda type_var: pa.lib.float64(),
+    TypeID.FIXED: lambda type_var: pa.lib.binary(length=type_var.length),
+    TypeID.FLOAT: lambda type_var: pa.lib.float32(),
+    TypeID.INTEGER: lambda type_var: pa.lib.int32(),
+    TypeID.LIST: lambda type_var: convert_field(type_var),
+    TypeID.LONG: lambda type_var: pa.lib.int64(),
+    TypeID.MAP: lambda type_var: convert_field(type_var),
+    TypeID.STRING: lambda type_var: pa.lib.string(),
+    TypeID.STRUCT: lambda type_var: convert_field(type_var),
+    TypeID.TIME: lambda type_var: pa.lib.time64("us"),
+    TypeID.TIMESTAMP: lambda type_var: pa.timestamp("us", tz="UTC" if type_var.adjust_to_utc else None),
+}
+
+
+def iceberg_to_arrow(iceberg_schema: Schema) -> pa.Schema:
+    """
+    Use an iceberg schema, to create an equivalent arrow schema with intact field_id metadata
+
+    Parameters
+    ----------
+    iceberg_schema : Schema
+        An iceberg schema to map
+
+    Returns
+    -------
+    pyarrow.Schema
+        returns an equivalent pyarrow Schema based on the iceberg schema provided. Performs
+    """
+    arrow_fields = []
+    for field in iceberg_schema.as_struct().fields:
+        arrow_fields.append(convert_field(field))
+
+    return pa.schema(arrow_fields,
+                     metadata={b'iceberg.schema': json.dumps(SchemaParser.to_dict(iceberg_schema)).encode("utf-8")})
+
+
+def convert_field(iceberg_field: NestedField) -> pa.Field:
+    """
+        Map an iceberg field to a pyarrow field. Recursively calls itself for nested fields
+        there is currently a limitation in the ability to convert map types since the pyarrow python bindings
+        don't expose a way to set fields for the key and value fields in a map
+
+        Parameters
+        ----------
+        iceberg_field: NestedField
+            An iceberg schema to map
+
+        Returns
+        -------
+        pa.Field
+            returns an equivalent pyarow Field based on the Nested Field.
+        """
+    if iceberg_field.type.is_primitive_type():
+        try:
+            arrow_field = ICEBERG_TO_ARROW_MAP[iceberg_field.type.type_id](iceberg_field.type)
+        except KeyError:
+            raise ValueError(f"Unable to convert {iceberg_field}")
+
+    elif iceberg_field.type.type_id == TypeID.STRUCT:
+        arrow_field = pa.struct([convert_field(field) for field in iceberg_field.type.fields])
+    elif iceberg_field.type.type_id == TypeID.LIST:
+        try:
+            arrow_field = pa.list_(ICEBERG_TO_ARROW_MAP[iceberg_field.type.type_id](iceberg_field.type.element_field))
+        except KeyError:
+            raise ValueError(f"Unable to convert {iceberg_field.type}")
+    elif iceberg_field.type.type_id == TypeID.MAP:
+        raise NotImplementedError("Unable to serialize Map types; python arrow bindings can't pass key/val metadata")

Review comment:
       As java ArrowSchemaUtil supports it, wondering if this is python limit?




-- 
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: issues-unsubscribe@iceberg.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] TGooch44 commented on pull request #2884: [python] Adding utility functions for converting iceberg to arrow

Posted by GitBox <gi...@apache.org>.
TGooch44 commented on pull request #2884:
URL: https://github.com/apache/iceberg/pull/2884#issuecomment-888567109


   cc: @jun-he 


-- 
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: issues-unsubscribe@iceberg.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] kainoa21 commented on a change in pull request #2884: [python] Adding utility functions for converting iceberg to arrow

Posted by GitBox <gi...@apache.org>.
kainoa21 commented on a change in pull request #2884:
URL: https://github.com/apache/iceberg/pull/2884#discussion_r694474816



##########
File path: python/iceberg/parquet/iceberg_to_arrow.py
##########
@@ -0,0 +1,107 @@
+# 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.
+
+
+import json
+from typing import Callable, Dict
+
+from iceberg.api import Schema
+from iceberg.api.types import NestedField, TypeID
+from iceberg.core import SchemaParser
+import pyarrow as pa
+
+
+ICEBERG_TO_ARROW_MAP: Dict[TypeID, Callable] = {
+    TypeID.BOOLEAN: lambda type_var: pa.lib.bool_(),
+    TypeID.BINARY: lambda type_var: pa.lib.binary(),
+    TypeID.DATE: lambda type_var: pa.lib.date32(),
+    TypeID.DECIMAL: lambda type_var: pa.lib.decimal128(type_var.precision, type_var.scale),
+    TypeID.DOUBLE: lambda type_var: pa.lib.float64(),
+    TypeID.FIXED: lambda type_var: pa.lib.binary(length=type_var.length),
+    TypeID.FLOAT: lambda type_var: pa.lib.float32(),
+    TypeID.INTEGER: lambda type_var: pa.lib.int32(),
+    TypeID.LIST: lambda type_var: convert_field(type_var),
+    TypeID.LONG: lambda type_var: pa.lib.int64(),
+    TypeID.MAP: lambda type_var: convert_field(type_var),
+    TypeID.STRING: lambda type_var: pa.lib.string(),
+    TypeID.STRUCT: lambda type_var: convert_field(type_var),
+    TypeID.TIME: lambda type_var: pa.lib.time64("us"),
+    TypeID.TIMESTAMP: lambda type_var: pa.timestamp("us", tz="UTC" if type_var.adjust_to_utc else None),
+}
+
+
+def iceberg_to_arrow(iceberg_schema: Schema) -> pa.Schema:
+    """
+    Use an iceberg schema, to create an equivalent arrow schema with intact field_id metadata
+
+    Parameters
+    ----------
+    iceberg_schema : Schema
+        An iceberg schema to map
+
+    Returns
+    -------
+    pyarrow.Schema
+        returns an equivalent pyarrow Schema based on the iceberg schema provided. Performs
+    """
+    arrow_fields = []
+    for field in iceberg_schema.as_struct().fields:
+        arrow_fields.append(convert_field(field))
+
+    return pa.schema(arrow_fields,
+                     metadata={b'iceberg.schema': json.dumps(SchemaParser.to_dict(iceberg_schema)).encode("utf-8")})
+
+
+def convert_field(iceberg_field: NestedField) -> pa.Field:
+    """
+        Map an iceberg field to a pyarrow field. Recursively calls itself for nested fields
+        there is currently a limitation in the ability to convert map types since the pyarrow python bindings
+        don't expose a way to set fields for the key and value fields in a map
+
+        Parameters
+        ----------
+        iceberg_field: NestedField
+            An iceberg schema to map
+
+        Returns
+        -------
+        pa.Field
+            returns an equivalent pyarow Field based on the Nested Field.
+        """
+    if iceberg_field.type.is_primitive_type():
+        try:
+            arrow_field = ICEBERG_TO_ARROW_MAP[iceberg_field.type.type_id](iceberg_field.type)
+        except KeyError:
+            raise ValueError(f"Unable to convert {iceberg_field}")
+
+    elif iceberg_field.type.type_id == TypeID.STRUCT:
+        arrow_field = pa.struct([convert_field(field) for field in iceberg_field.type.fields])
+    elif iceberg_field.type.type_id == TypeID.LIST:
+        try:
+            arrow_field = pa.list_(ICEBERG_TO_ARROW_MAP[iceberg_field.type.type_id](iceberg_field.type.element_field))
+        except KeyError:
+            raise ValueError(f"Unable to convert {iceberg_field.type}")
+    elif iceberg_field.type.type_id == TypeID.MAP:
+        raise NotImplementedError("Unable to serialize Map types; python arrow bindings can't pass key/val metadata")

Review comment:
       PR for creating a map datatype with fields: https://github.com/apache/arrow/pull/10981




-- 
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: issues-unsubscribe@iceberg.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org


[GitHub] [iceberg] TGooch44 commented on a change in pull request #2884: [python] Adding utility functions for converting iceberg to arrow

Posted by GitBox <gi...@apache.org>.
TGooch44 commented on a change in pull request #2884:
URL: https://github.com/apache/iceberg/pull/2884#discussion_r678623884



##########
File path: python/iceberg/parquet/iceberg_to_arrow.py
##########
@@ -0,0 +1,107 @@
+# 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.
+
+
+import json
+from typing import Callable, Dict
+
+from iceberg.api import Schema
+from iceberg.api.types import NestedField, TypeID
+from iceberg.core import SchemaParser
+import pyarrow as pa
+
+
+ICEBERG_TO_ARROW_MAP: Dict[TypeID, Callable] = {
+    TypeID.BOOLEAN: lambda type_var: pa.lib.bool_(),
+    TypeID.BINARY: lambda type_var: pa.lib.binary(),
+    TypeID.DATE: lambda type_var: pa.lib.date32(),
+    TypeID.DECIMAL: lambda type_var: pa.lib.decimal128(type_var.precision, type_var.scale),
+    TypeID.DOUBLE: lambda type_var: pa.lib.float64(),
+    TypeID.FIXED: lambda type_var: pa.lib.binary(length=type_var.length),
+    TypeID.FLOAT: lambda type_var: pa.lib.float32(),
+    TypeID.INTEGER: lambda type_var: pa.lib.int32(),
+    TypeID.LIST: lambda type_var: convert_field(type_var),
+    TypeID.LONG: lambda type_var: pa.lib.int64(),
+    TypeID.MAP: lambda type_var: convert_field(type_var),
+    TypeID.STRING: lambda type_var: pa.lib.string(),
+    TypeID.STRUCT: lambda type_var: convert_field(type_var),
+    TypeID.TIME: lambda type_var: pa.lib.time64("us"),
+    TypeID.TIMESTAMP: lambda type_var: pa.timestamp("us", tz="UTC" if type_var.adjust_to_utc else None),
+}
+
+
+def iceberg_to_arrow(iceberg_schema: Schema) -> pa.Schema:
+    """
+    Use an iceberg schema, to create an equivalent arrow schema with intact field_id metadata
+
+    Parameters
+    ----------
+    iceberg_schema : Schema
+        An iceberg schema to map
+
+    Returns
+    -------
+    pyarrow.Schema
+        returns an equivalent pyarrow Schema based on the iceberg schema provided. Performs
+    """
+    arrow_fields = []
+    for field in iceberg_schema.as_struct().fields:
+        arrow_fields.append(convert_field(field))
+
+    return pa.schema(arrow_fields,
+                     metadata={b'iceberg.schema': json.dumps(SchemaParser.to_dict(iceberg_schema)).encode("utf-8")})
+
+
+def convert_field(iceberg_field: NestedField) -> pa.Field:
+    """
+        Map an iceberg field to a pyarrow field. Recursively calls itself for nested fields
+        there is currently a limitation in the ability to convert map types since the pyarrow python bindings
+        don't expose a way to set fields for the key and value fields in a map
+
+        Parameters
+        ----------
+        iceberg_field: NestedField
+            An iceberg schema to map
+
+        Returns
+        -------
+        pa.Field
+            returns an equivalent pyarow Field based on the Nested Field.
+        """
+    if iceberg_field.type.is_primitive_type():
+        try:
+            arrow_field = ICEBERG_TO_ARROW_MAP[iceberg_field.type.type_id](iceberg_field.type)
+        except KeyError:
+            raise ValueError(f"Unable to convert {iceberg_field}")
+
+    elif iceberg_field.type.type_id == TypeID.STRUCT:
+        arrow_field = pa.struct([convert_field(field) for field in iceberg_field.type.fields])
+    elif iceberg_field.type.type_id == TypeID.LIST:
+        try:
+            arrow_field = pa.list_(ICEBERG_TO_ARROW_MAP[iceberg_field.type.type_id](iceberg_field.type.element_field))
+        except KeyError:
+            raise ValueError(f"Unable to convert {iceberg_field.type}")
+    elif iceberg_field.type.type_id == TypeID.MAP:
+        raise NotImplementedError("Unable to serialize Map types; python arrow bindings can't pass key/val metadata")

Review comment:
       The binding in python to create a map field takes a Datatype where as list and struct take either datatypes or fields.
   https://arrow.apache.org/docs/python/generated/pyarrow.map_.html
   
    I'll ask their user/dev list if there's any other API available to do this and if not open an issue in the arrow project.  I think it still may be useful to have something out even if it doesn't have full type support.  A huge portion of our internal use-cases are just reading/writing strings/ints/longs.




-- 
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: issues-unsubscribe@iceberg.apache.org

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



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org