Fokko commented on code in PR #7831:
URL: https://github.com/apache/iceberg/pull/7831#discussion_r1259665559


##########
python/pyiceberg/utils/file_stats.py:
##########
@@ -0,0 +1,333 @@
+#  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 struct
+from typing import (
+    Any,
+    Dict,
+    List,
+    Union,
+)
+
+import pyarrow.lib
+import pyarrow.parquet as pq
+
+from pyiceberg.manifest import DataFile, FileFormat
+from pyiceberg.schema import Schema, SchemaVisitor, visit
+from pyiceberg.types import (
+    IcebergType,
+    ListType,
+    MapType,
+    NestedField,
+    PrimitiveType,
+    StructType,
+)
+
+BOUND_TRUNCATED_LENGHT = 16
+
+# Serialization rules: 
https://iceberg.apache.org/spec/#binary-single-value-serialization
+#
+# Type      Binary serialization
+# boolean   0x00 for false, non-zero byte for true
+# int       Stored as 4-byte little-endian
+# long      Stored as 8-byte little-endian
+# float     Stored as 4-byte little-endian
+# double    Stored as 8-byte little-endian
+# date      Stores days from the 1970-01-01 in an 4-byte little-endian int
+# time      Stores microseconds from midnight in an 8-byte little-endian long
+# timestamp without zone       Stores microseconds from 1970-01-01 
00:00:00.000000 in an 8-byte little-endian long
+# timestamp with zone  Stores microseconds from 1970-01-01 00:00:00.000000 UTC 
in an 8-byte little-endian long
+# string    UTF-8 bytes (without length)
+# uuid      16-byte big-endian value, see example in Appendix B
+# fixed(L)  Binary value
+# binary    Binary value (without length)
+#
+
+
+def bool_to_avro(value: bool) -> bytes:
+    return struct.pack("?", value)
+
+
+def int32_to_avro(value: int) -> bytes:
+    return struct.pack("<i", value)
+
+
+def int64_to_avro(value: int) -> bytes:
+    return struct.pack("<q", value)
+
+
+def float_to_avro(value: float) -> bytes:
+    return struct.pack("<f", value)
+
+
+def double_to_avro(value: float) -> bytes:
+    return struct.pack("<d", value)
+
+
+def bytes_to_avro(value: Union[bytes, str]) -> bytes:
+    if type(value) == str:
+        return value.encode()
+    else:
+        assert isinstance(value, bytes)  # appeases mypy
+        return value
+
+
+class StatsAggregator:
+    def __init__(self, type_string: str):
+        self.current_min: Any = None
+        self.current_max: Any = None
+        self.serialize: Any = None
+
+        if type_string == "BOOLEAN":
+            self.serialize = bool_to_avro
+        elif type_string == "INT32":
+            self.serialize = int32_to_avro
+        elif type_string == "INT64":
+            self.serialize = int64_to_avro
+        elif type_string == "INT96":
+            raise NotImplementedError("Statistics not implemented for INT96 
physical type")
+        elif type_string == "FLOAT":
+            self.serialize = float_to_avro
+        elif type_string == "DOUBLE":
+            self.serialize = double_to_avro
+        elif type_string == "BYTE_ARRAY":
+            self.serialize = bytes_to_avro
+        elif type_string == "FIXED_LEN_BYTE_ARRAY":
+            self.serialize = bytes_to_avro
+        else:
+            raise AssertionError(f"Unknown physical type {type_string}")
+
+    def add_min(self, val: bytes) -> None:
+        if not self.current_min:
+            self.current_min = val
+        elif val < self.current_min:
+            self.current_min = val
+
+    def add_max(self, val: bytes) -> None:
+        if not self.current_max:
+            self.current_max = val
+        elif self.current_max < val:
+            self.current_max = val
+
+    def get_min(self) -> bytes:
+        return self.serialize(self.current_min)[:BOUND_TRUNCATED_LENGHT]
+
+    def get_max(self) -> bytes:
+        return self.serialize(self.current_max)[:BOUND_TRUNCATED_LENGHT]
+
+
+def fill_parquet_file_metadata(
+    df: DataFile, metadata: pq.FileMetaData, col_path_2_iceberg_id: Dict[str, 
int], file_size: int
+) -> None:
+    """
+    Computes and fills the following fields of the DataFile object.
+
+    - file_format
+    - record_count
+    - file_size_in_bytes
+    - column_sizes
+    - value_counts
+    - null_value_counts
+    - nan_value_counts
+    - lower_bounds
+    - upper_bounds
+    - split_offsets
+
+    Args:
+        df (DataFile): A DataFile object representing the Parquet file for 
which metadata is to be filled.
+        metadata (pyarrow.parquet.FileMetaData): A pyarrow metadata object.
+        col_path_2_iceberg_id: A mapping of column paths as in the 
`path_in_schema` attribute of the colum

Review Comment:
   Since Arrow is column-oriented, I'm sure that it will follow the order of 
the write schema:
   
   
![image](https://github.com/apache/iceberg/assets/1134248/5dd5016e-7761-4cdc-a169-d3c4744c581b)
   
   The reason I try to avoid using too many internal details from PyArrow is 
that we support PyArrow `[9.0.0, 12.0.1]` currently. There is no guarantee that 
all these internals stay the same, therefore I think we should do as much as 
possible within our own control (also regarding the internal Parquet types, or 
how the column names are structured).
   
   We already have the write schema, so we can easily filter out the primitive 
types:
   
   ```python
   class 
PyArrowStatisticsCollector(PreOrderSchemaVisitor[List[StatisticsCollector]]):
       _field_id = 0
       _schema: Schema
       _properties: Properties
   
       def __init__(self, schema: Schema, properties: Dict[str, str]):
           self._schema = schema
           self._properties = properties
   
       def schema(self, schema: Schema, struct_result: Callable[[], 
List[StatisticsCollector]]) -> List[StatisticsCollector]:
           return struct_result()
   
       def struct(self, struct: StructType, field_results: List[Callable[[], 
List[StatisticsCollector]]]) -> List[StatisticsCollector]:
           return list(chain(*[result() for result in field_results]))
   
       def field(self, field: NestedField, field_result: Callable[[], 
List[StatisticsCollector]]) -> List[StatisticsCollector]:
           self._field_id = field.field_id
           result = field_result()
           return result
   
       def list(self, list_type: ListType, element_result: Callable[[], 
List[StatisticsCollector]]) -> List[StatisticsCollector]:
           self._field_id = list_type.element_id
           return element_result()
   
       def map(self, map_type: MapType, key_result: Callable[[], 
List[StatisticsCollector]], value_result: Callable[[], 
List[StatisticsCollector]]) -> List[StatisticsCollector]:
           self._field_id = map_type.key_id
           k = key_result()
           self._field_id = map_type.value_id
           v = value_result()
           return k + v
   
       def primitive(self, primitive: PrimitiveType) -> 
List[StatisticsCollector]:
           return [StatisticsCollector(
               field_id=self._field_id,
               iceberg_type=primitive,
               mode=MetricsMode.TRUNC
               # schema
               # 
self._properties.get(f"write.metadata.metrics.column.{schema.find_column_name(self._field_id)}")
           )]
   ```
   
   This way we get a nice list of columns that we need to collect statistics 
for. We have:
   
   ```python
   @dataclass(frozen=True)
   class StatisticsCollector:
       field_id: int
       iceberg_type: PrimitiveType
       mode: MetricsMode
   ```
   
   Where we can use the `field_id` to properly populate the maps, and the 
`iceberg_type` to feed into `to_bytes` to do the conversion (so we don't have 
to have yet another one for PyArrow).
   
   I did a quick test, and it seems to work:
   ```python
   def test_complex_schema(table_schema_nested: Schema):
       tbl = pa.Table.from_pydict({
           "foo": ["a", "b"],
           "bar": [1, 2],
           "baz": [False, True],
           "qux": [["a", "b"], ["c", "d"]],
           "quux": [[("a", (("aa", 1), ("ab", 2)))], [("b", (("ba", 3), ("bb", 
4)))]],
           "location": [[(52.377956, 4.897070), (4.897070, -122.431297)],
                        [(43.618881, -116.215019), (41.881832, -87.623177)]],
           "person": [("Fokko", 33), ("Max", 42)]  # Possible data quality issue
       },
           schema=schema_to_pyarrow(table_schema_nested)
       )
       stats_columns = pre_order_visit(table_schema_nested, 
PyArrowStatisticsCollector(table_schema_nested, {}))
   
       visited_paths = []
   
       def file_visitor(written_file: Any) -> None:
           visited_paths.append(written_file)
   
       with TemporaryDirectory() as tmpdir:
           pq.write_to_dataset(tbl, tmpdir, file_visitor=file_visitor)
   
       assert visited_paths[0].metadata.num_columns == len(stats_columns)
   ```



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to