Fokko commented on code in PR #7831:
URL: https://github.com/apache/iceberg/pull/7831#discussion_r1259416267
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1013,3 +1027,359 @@ def map_key_partner(self, partner_map:
Optional[pa.Array]) -> Optional[pa.Array]
def map_value_partner(self, partner_map: Optional[pa.Array]) ->
Optional[pa.Array]:
return partner_map.items if isinstance(partner_map, pa.MapArray) else
None
+
+
+BOUND_TRUNCATED_LENGHT = 16
+TRUNCATION_EXPR = r"^truncate\((\d+)\)$"
+
+logger = logging.getLogger(__name__)
+
+# 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_BOOL.pack(value)
+
+
+def int32_to_avro(value: int) -> bytes:
+ return STRUCT_INT32.pack(value)
+
+
+def int64_to_avro(value: int) -> bytes:
+ return STRUCT_INT64.pack(value)
+
+
+def float_to_avro(value: float) -> bytes:
+ return STRUCT_FLOAT.pack(value)
+
+
+def double_to_avro(value: float) -> bytes:
+ return STRUCT_DOUBLE.pack(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, trunc_length: Optional[int] = None)
-> None:
+ self.current_min: Any = None
+ self.current_max: Any = None
+ self.serialize: Any = None
+ self.trunc_lenght = trunc_length
+
+ 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 self.current_min is None:
+ self.current_min = val
+ else:
+ self.current_min = min(val, self.current_min)
+
+ def add_max(self, val: bytes) -> None:
+ if self.current_max is None:
+ self.current_max = val
+ else:
+ self.current_max = max(self.current_max, val)
+
+ def get_min(self) -> bytes:
+ return self.serialize(self.current_min)[: self.trunc_lenght]
+
+ def get_max(self) -> bytes:
+ return self.serialize(self.current_max)[: self.trunc_lenght]
+
+
+class MetricsMode(Enum):
+ NONE = 0
+ COUNTS = 1
+ TRUNC = 2
Review Comment:
```suggestion
TRUNCATE = 2
```
##########
python/tests/io/test_pyarrow.py:
##########
@@ -1330,3 +1341,485 @@ def test_pyarrow_wrap_fsspec(example_task:
FileScanTask, table_schema_simple: Sc
bar: [[1,2,3]]
baz: [[true,false,null]]"""
)
+
+
+def construct_test_table() -> pa.Buffer:
+ schema = pa.schema(
+ [
+ pa.field("strings", pa.string()),
+ pa.field("floats", pa.float64()),
+ pa.field("list", pa.list_(pa.int64())),
+ pa.field("maps", pa.map_(pa.int64(), pa.int64())),
+ ]
+ )
+
+ _strings = ["zzzzzzzzzzzzzzzzzzzz", "rrrrrrrrrrrrrrrrrrrr", None,
"aaaaaaaaaaaaaaaaaaaa"]
+
+ _floats = [3.14, math.nan, 1.69, 100]
+
+ _list = [[1, 2, 3], [4, 5, 6], None, [7, 8, 9]]
+
+ _maps: List[Optional[Dict[int, int]]] = [
+ {1: 2, 3: 4},
+ None,
+ {5: 6},
+ {},
+ ]
+
+ table = pa.Table.from_pydict(
+ {
+ "strings": _strings,
+ "floats": _floats,
+ "list": _list,
+ "maps": _maps,
+ },
+ schema=schema,
+ )
+ f = pa.BufferOutputStream()
+
+ metadata_collector: List[Any] = []
+ writer = pq.ParquetWriter(f, table.schema,
metadata_collector=metadata_collector)
+
+ writer.write_table(table)
+ writer.close()
+
+ print(writer.writer)
+ print(writer.writer.metadata)
+
+ mapping = {"strings": 1, "floats": 2, "list.list.item": 3,
"maps.key_value.key": 4, "maps.key_value.value": 5}
+
+ return f.getvalue(), metadata_collector[0], mapping
+
+
+def test_record_count() -> None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ fill_parquet_file_metadata(datafile, metadata, mapping, len(file_bytes))
+
+ assert datafile.record_count == 4
+
+
+def test_file_size() -> None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ fill_parquet_file_metadata(datafile, metadata, mapping, len(file_bytes))
+
+ assert datafile.file_size_in_bytes == len(file_bytes)
+
+
+def test_value_counts() -> None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ fill_parquet_file_metadata(datafile, metadata, mapping, len(file_bytes))
+
+ assert len(datafile.value_counts) == 5
+ assert datafile.value_counts[1] == 4
+ assert datafile.value_counts[2] == 4
+ assert datafile.value_counts[3] == 10 # 3 lists with 3 items and a None
value
+ assert datafile.value_counts[4] == 5
+ assert datafile.value_counts[5] == 5
+
+
+def test_column_sizes() -> None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ fill_parquet_file_metadata(datafile, metadata, mapping, len(file_bytes))
+
+ assert len(datafile.column_sizes) == 5
+ # these values are an artifact of how the write_table encodes the columns
+ assert datafile.column_sizes[1] == 116
+ assert datafile.column_sizes[2] == 119
+ assert datafile.column_sizes[3] == 151
+ assert datafile.column_sizes[4] == 117
+ assert datafile.column_sizes[5] == 117
+
+
+def test_null_and_nan_counts() -> None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ fill_parquet_file_metadata(datafile, metadata, mapping, len(file_bytes))
+
+ assert len(datafile.null_value_counts) == 5
+ assert datafile.null_value_counts[1] == 1
+ assert datafile.null_value_counts[2] == 0
+ assert datafile.null_value_counts[3] == 1
+ assert datafile.null_value_counts[4] == 2
+ assert datafile.null_value_counts[5] == 2
+
+ # #arrow does not include this in the statistics
+ # assert len(datafile.nan_value_counts) == 3
+ # assert datafile.nan_value_counts[1] == 0
+ # assert datafile.nan_value_counts[2] == 1
+ # assert datafile.nan_value_counts[3] == 0
+
+
+def test_bounds() -> None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ fill_parquet_file_metadata(datafile, metadata, mapping, len(file_bytes))
+
+ assert len(datafile.lower_bounds) == 2
+ assert datafile.lower_bounds[1].decode() ==
"aaaaaaaaaaaaaaaaaaaa"[:BOUND_TRUNCATED_LENGHT]
+ assert datafile.lower_bounds[2] == STRUCT_DOUBLE.pack(1.69)
+
+ assert len(datafile.upper_bounds) == 2
+ assert datafile.upper_bounds[1].decode() ==
"zzzzzzzzzzzzzzzzzzzz"[:BOUND_TRUNCATED_LENGHT]
+ assert datafile.upper_bounds[2] == STRUCT_DOUBLE.pack(100)
+
+
+def test_metrics_mode_none(example_table_metadata_v2: Dict[str, Any]) -> None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ table_metadata = TableMetadataUtil.parse_obj(example_table_metadata_v2)
+ table_metadata.properties["write.metadata.metrics.default"] = "none"
+ fill_parquet_file_metadata(
+ datafile,
+ metadata,
+ mapping,
+ len(file_bytes),
+ table_metadata,
+ )
+
+ assert len(datafile.value_counts) == 0
+ assert len(datafile.null_value_counts) == 0
+ assert len(datafile.nan_value_counts) == 0
+ assert len(datafile.lower_bounds) == 0
+ assert len(datafile.upper_bounds) == 0
+
+
+def test_metrics_mode_counts(example_table_metadata_v2: Dict[str, Any]) ->
None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ table_metadata = TableMetadataUtil.parse_obj(example_table_metadata_v2)
+ table_metadata.properties["write.metadata.metrics.default"] = "counts"
+ fill_parquet_file_metadata(
+ datafile,
+ metadata,
+ mapping,
+ len(file_bytes),
+ table_metadata,
+ )
+
+ assert len(datafile.value_counts) == 5
+ assert len(datafile.null_value_counts) == 5
+ assert len(datafile.nan_value_counts) == 0
+ assert len(datafile.lower_bounds) == 0
+ assert len(datafile.upper_bounds) == 0
+
+
+def test_metrics_mode_full(example_table_metadata_v2: Dict[str, Any]) -> None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ table_metadata = TableMetadataUtil.parse_obj(example_table_metadata_v2)
+ table_metadata.properties["write.metadata.metrics.default"] = "full"
+ fill_parquet_file_metadata(
+ datafile,
+ metadata,
+ mapping,
+ len(file_bytes),
+ table_metadata,
+ )
+
+ assert len(datafile.value_counts) == 5
+ assert len(datafile.null_value_counts) == 5
+ assert len(datafile.nan_value_counts) == 0
+
+ assert len(datafile.lower_bounds) == 2
+ assert datafile.lower_bounds[1].decode() == "aaaaaaaaaaaaaaaaaaaa"
+ assert datafile.lower_bounds[2] == STRUCT_DOUBLE.pack(1.69)
+
+ assert len(datafile.upper_bounds) == 2
+ assert datafile.upper_bounds[1].decode() == "zzzzzzzzzzzzzzzzzzzz"
+ assert datafile.upper_bounds[2] == STRUCT_DOUBLE.pack(100)
+
+
+def test_metrics_mode_non_default_trunc(example_table_metadata_v2: Dict[str,
Any]) -> None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ table_metadata = TableMetadataUtil.parse_obj(example_table_metadata_v2)
+ table_metadata.properties["write.metadata.metrics.default"] = "truncate(2)"
+ fill_parquet_file_metadata(
+ datafile,
+ metadata,
+ mapping,
+ len(file_bytes),
+ table_metadata,
+ )
+
+ assert len(datafile.value_counts) == 5
+ assert len(datafile.null_value_counts) == 5
+ assert len(datafile.nan_value_counts) == 0
+
+ assert len(datafile.lower_bounds) == 2
+ assert datafile.lower_bounds[1].decode() == "aa"
+ assert datafile.lower_bounds[2] == STRUCT_DOUBLE.pack(1.69)[:2]
+
+ assert len(datafile.upper_bounds) == 2
+ assert datafile.upper_bounds[1].decode() == "zz"
+ assert datafile.upper_bounds[2] == STRUCT_DOUBLE.pack(100)[:2]
+
+
+def test_column_metrics_mode(example_table_metadata_v2: Dict[str, Any]) ->
None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ table_metadata = TableMetadataUtil.parse_obj(example_table_metadata_v2)
+ table_metadata.properties["write.metadata.metrics.default"] = "truncate(2)"
+ table_metadata.properties["write.metadata.metrics.column.strings"] = "none"
+ fill_parquet_file_metadata(
+ datafile,
+ metadata,
+ mapping,
+ len(file_bytes),
+ table_metadata,
+ )
+
+ assert len(datafile.value_counts) == 4
+ assert len(datafile.null_value_counts) == 4
+ assert len(datafile.nan_value_counts) == 0
+
+ assert len(datafile.lower_bounds) == 1
+ assert datafile.lower_bounds[2] == STRUCT_DOUBLE.pack(1.69)[:2]
+
+ assert len(datafile.upper_bounds) == 1
+ assert datafile.upper_bounds[2] == STRUCT_DOUBLE.pack(100)[:2]
+
+
+def test_offsets() -> None:
+ (file_bytes, metadata, mapping) = construct_test_table()
+
+ datafile = DataFile()
+ fill_parquet_file_metadata(datafile, metadata, mapping, len(file_bytes))
+
+ assert datafile.split_offsets is not None
+ assert len(datafile.split_offsets) == 1
+ assert datafile.split_offsets[0] == 4
+
+
+def test_dataset() -> pa.Buffer:
+ schema = pa.schema([pa.field("ints", pa.int64()), pa.field("even",
pa.bool_())])
+
+ _ints = [0, 2, 4, 8, 1, 3, 5, 7]
+ parity = [True, True, True, True, False, False, False, False]
+
+ table = pa.Table.from_pydict({"ints": _ints, "even": parity},
schema=schema)
+
+ visited_paths = []
+
+ def file_visitor(written_file: Any) -> None:
+ visited_paths.append(written_file)
+
+ with TemporaryDirectory() as tmpdir:
+ pq.write_to_dataset(table, tmpdir, partition_cols=["even"],
file_visitor=file_visitor)
+
+ even = None
+ odd = None
+
+ assert len(visited_paths) == 2
+
+ for written_file in visited_paths:
+ df = DataFile()
+
+ fill_parquet_file_metadata(df, written_file.metadata, {"ints": 1,
"even": 2}, written_file.size)
+
+ if "even=true" in written_file.path:
+ even = df
+
+ if "even=false" in written_file.path:
+ odd = df
+
+ assert even is not None
+ assert odd is not None
+
+ assert len(even.value_counts) == 1
+ assert even.value_counts[1] == 4
+ assert len(even.lower_bounds) == 1
+ assert even.lower_bounds[1] == STRUCT_INT64.pack(0)
+ assert len(even.upper_bounds) == 1
+ assert even.upper_bounds[1] == STRUCT_INT64.pack(8)
+
+ assert len(odd.value_counts) == 1
+ assert odd.value_counts[1] == 4
+ assert len(odd.lower_bounds) == 1
+ assert odd.lower_bounds[1] == STRUCT_INT64.pack(1)
+ assert len(odd.upper_bounds) == 1
+ assert odd.upper_bounds[1] == STRUCT_INT64.pack(7)
+
+
+def test_schema_mapping() -> None:
Review Comment:
You can re-use an existing fixture here.
```suggestion
def test_schema_mapping(table_schema_nested: Schema) -> None:
```
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1013,3 +1027,359 @@ def map_key_partner(self, partner_map:
Optional[pa.Array]) -> Optional[pa.Array]
def map_value_partner(self, partner_map: Optional[pa.Array]) ->
Optional[pa.Array]:
return partner_map.items if isinstance(partner_map, pa.MapArray) else
None
+
+
+BOUND_TRUNCATED_LENGHT = 16
+TRUNCATION_EXPR = r"^truncate\((\d+)\)$"
+
+logger = logging.getLogger(__name__)
+
+# 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_BOOL.pack(value)
+
+
+def int32_to_avro(value: int) -> bytes:
+ return STRUCT_INT32.pack(value)
+
+
+def int64_to_avro(value: int) -> bytes:
+ return STRUCT_INT64.pack(value)
+
+
+def float_to_avro(value: float) -> bytes:
+ return STRUCT_FLOAT.pack(value)
+
+
+def double_to_avro(value: float) -> bytes:
+ return STRUCT_DOUBLE.pack(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, trunc_length: Optional[int] = None)
-> None:
+ self.current_min: Any = None
+ self.current_max: Any = None
+ self.serialize: Any = None
+ self.trunc_lenght = trunc_length
+
+ 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 self.current_min is None:
+ self.current_min = val
+ else:
+ self.current_min = min(val, self.current_min)
+
+ def add_max(self, val: bytes) -> None:
+ if self.current_max is None:
+ self.current_max = val
+ else:
+ self.current_max = max(self.current_max, val)
+
+ def get_min(self) -> bytes:
+ return self.serialize(self.current_min)[: self.trunc_lenght]
+
+ def get_max(self) -> bytes:
+ return self.serialize(self.current_max)[: self.trunc_lenght]
+
+
+class MetricsMode(Enum):
+ NONE = 0
+ COUNTS = 1
+ TRUNC = 2
+ FULL = 3
+
+
+def match_metrics_mode(mode: str) -> Tuple[MetricsMode, Optional[int]]:
+ m = re.match(TRUNCATION_EXPR, mode)
+
+ if m:
+ return MetricsMode.TRUNC, int(m[1])
+ elif mode == "none":
+ return MetricsMode.NONE, None
+ elif mode == "counts":
+ return MetricsMode.COUNTS, None
+ elif mode == "full":
+ return MetricsMode.FULL, None
+ else:
+ raise AssertionError(f"Unsupported metrics mode {mode}")
+
+
+def fill_parquet_file_metadata(
+ df: DataFile,
+ metadata: pq.FileMetaData,
+ col_path_2_iceberg_id: Dict[str, int],
+ file_size: int,
+ table_metadata: Optional[TableMetadata] = None,
+) -> 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
+ metadata to iceberg schema IDs. For scalar columns this will be
the column name. For complex types
+ it could be something like `my_map.key_value.value`
+ file_size (int): The total compressed file size cannot be retrieved
from the metadata and hence has to
+ be passed here. Depending on the kind of file system and pyarrow
library call used, different
+ ways to obtain this value might be appropriate.
+ """
+ col_index_2_id = {}
+
+ col_names = {p.split(".")[0] for p in col_path_2_iceberg_id.keys()}
+
+ metrics_modes = {n: MetricsMode.TRUNC for n in col_names}
+ trunc_lengths: Dict[str, Optional[int]] = {n: BOUND_TRUNCATED_LENGHT for n
in col_names}
+
+ if table_metadata:
+ default_mode =
table_metadata.properties.get("write.metadata.metrics.default")
Review Comment:
Can we move this one into a constant?
##########
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
+ metadata to iceberg schema IDs. For scalar columns this will be
the column name. For complex types
+ it could be something like `my_map.key_value.value`
+ file_size (int): The total compressed file size cannot be retrieved
from the metadata and hence has to
+ be passed here. Depending on the kind of file system and pyarrow
library call used, different
+ ways to obtain this value might be appropriate.
+ """
+ col_index_2_id = {}
+
+ col_names = set(metadata.schema.names)
+
+ first_group = metadata.row_group(0)
+
+ for c in range(metadata.num_columns):
+ column = first_group.column(c)
+ col_path = column.path_in_schema
+
+ if col_path in col_path_2_iceberg_id:
+ col_index_2_id[c] = col_path_2_iceberg_id[col_path]
+ else:
+ raise AssertionError(f"Column path {col_path} couldn't be mapped
to an iceberg ID")
+
+ column_sizes: Dict[int, int] = {}
+ value_counts: Dict[int, int] = {}
+ split_offsets: List[int] = []
+
+ null_value_counts: Dict[int, int] = {}
+ nan_value_counts: Dict[int, int] = {}
+
+ col_aggs = {}
+
+ for r in range(metadata.num_row_groups):
+ # References:
+ #
https://github.com/apache/iceberg/blob/fc381a81a1fdb8f51a0637ca27cd30673bd7aad3/parquet/src/main/java/org/apache/iceberg/parquet/ParquetUtil.java#L232
+ #
https://github.com/apache/parquet-mr/blob/ac29db4611f86a07cc6877b416aa4b183e09b353/parquet-hadoop/src/main/java/org/apache/parquet/hadoop/metadata/ColumnChunkMetaData.java#L184
+
+ row_group = metadata.row_group(r)
+
+ data_offset = row_group.column(0).data_page_offset
+ dictionary_offset = row_group.column(0).dictionary_page_offset
+
+ if row_group.column(0).has_dictionary_page and dictionary_offset <
data_offset:
+ split_offsets.append(dictionary_offset)
+ else:
+ split_offsets.append(data_offset)
+
+ for c in range(metadata.num_columns):
+ col_id = col_index_2_id[c]
+
+ column = row_group.column(c)
+
+ column_sizes[col_id] = column_sizes.get(col_id, 0) +
column.total_compressed_size
+ value_counts[col_id] = value_counts.get(col_id, 0) +
column.num_values
+
+ if column.is_stats_set:
+ try:
+ statistics = column.statistics
+
+ null_value_counts[col_id] = null_value_counts.get(col_id,
0) + statistics.null_count
+
+ if column.path_in_schema in col_names:
+ # Iceberg seems to only have statistics for scalar
columns
+
+ if col_id not in col_aggs:
+ col_aggs[col_id] =
StatsAggregator(statistics.physical_type)
+
+ col_aggs[col_id].add_min(statistics.min)
Review Comment:
Fair point, thanks for the context
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1013,3 +1027,359 @@ def map_key_partner(self, partner_map:
Optional[pa.Array]) -> Optional[pa.Array]
def map_value_partner(self, partner_map: Optional[pa.Array]) ->
Optional[pa.Array]:
return partner_map.items if isinstance(partner_map, pa.MapArray) else
None
+
+
+BOUND_TRUNCATED_LENGHT = 16
+TRUNCATION_EXPR = r"^truncate\((\d+)\)$"
+
+logger = logging.getLogger(__name__)
+
+# 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:
Review Comment:
When we use the Iceberg types, then we can re-use `to_bytes`:
https://github.com/apache/iceberg/blob/62cb7b5c50451085d6e59f0594292bf883af4220/python/pyiceberg/conversions.py#L154-L166
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1013,3 +1027,359 @@ def map_key_partner(self, partner_map:
Optional[pa.Array]) -> Optional[pa.Array]
def map_value_partner(self, partner_map: Optional[pa.Array]) ->
Optional[pa.Array]:
return partner_map.items if isinstance(partner_map, pa.MapArray) else
None
+
+
+BOUND_TRUNCATED_LENGHT = 16
+TRUNCATION_EXPR = r"^truncate\((\d+)\)$"
+
+logger = logging.getLogger(__name__)
+
+# 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_BOOL.pack(value)
+
+
+def int32_to_avro(value: int) -> bytes:
+ return STRUCT_INT32.pack(value)
+
+
+def int64_to_avro(value: int) -> bytes:
+ return STRUCT_INT64.pack(value)
+
+
+def float_to_avro(value: float) -> bytes:
+ return STRUCT_FLOAT.pack(value)
+
+
+def double_to_avro(value: float) -> bytes:
+ return STRUCT_DOUBLE.pack(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, trunc_length: Optional[int] = None)
-> None:
+ self.current_min: Any = None
+ self.current_max: Any = None
+ self.serialize: Any = None
+ self.trunc_lenght = trunc_length
+
+ 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 self.current_min is None:
+ self.current_min = val
+ else:
+ self.current_min = min(val, self.current_min)
+
+ def add_max(self, val: bytes) -> None:
+ if self.current_max is None:
+ self.current_max = val
+ else:
+ self.current_max = max(self.current_max, val)
+
+ def get_min(self) -> bytes:
+ return self.serialize(self.current_min)[: self.trunc_lenght]
+
+ def get_max(self) -> bytes:
+ return self.serialize(self.current_max)[: self.trunc_lenght]
+
+
+class MetricsMode(Enum):
+ NONE = 0
+ COUNTS = 1
+ TRUNC = 2
+ FULL = 3
+
+
+def match_metrics_mode(mode: str) -> Tuple[MetricsMode, Optional[int]]:
+ m = re.match(TRUNCATION_EXPR, mode)
+
+ if m:
+ return MetricsMode.TRUNC, int(m[1])
+ elif mode == "none":
+ return MetricsMode.NONE, None
+ elif mode == "counts":
+ return MetricsMode.COUNTS, None
+ elif mode == "full":
+ return MetricsMode.FULL, None
+ else:
+ raise AssertionError(f"Unsupported metrics mode {mode}")
+
+
+def fill_parquet_file_metadata(
+ df: DataFile,
+ metadata: pq.FileMetaData,
+ col_path_2_iceberg_id: Dict[str, int],
+ file_size: int,
+ table_metadata: Optional[TableMetadata] = None,
+) -> 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
+ metadata to iceberg schema IDs. For scalar columns this will be
the column name. For complex types
+ it could be something like `my_map.key_value.value`
+ file_size (int): The total compressed file size cannot be retrieved
from the metadata and hence has to
+ be passed here. Depending on the kind of file system and pyarrow
library call used, different
+ ways to obtain this value might be appropriate.
+ """
+ col_index_2_id = {}
+
+ col_names = {p.split(".")[0] for p in col_path_2_iceberg_id.keys()}
+
+ metrics_modes = {n: MetricsMode.TRUNC for n in col_names}
+ trunc_lengths: Dict[str, Optional[int]] = {n: BOUND_TRUNCATED_LENGHT for n
in col_names}
+
+ if table_metadata:
+ default_mode =
table_metadata.properties.get("write.metadata.metrics.default")
+
+ if default_mode:
+ m, t = match_metrics_mode(default_mode)
+
+ metrics_modes = {n: m for n in col_names}
+ trunc_lengths = {n: t for n in col_names}
+
+ for col_name in col_names:
+ col_mode =
table_metadata.properties.get(f"write.metadata.metrics.column.{col_name}")
Review Comment:
I'm afraid that this isn't correct. Let's consider the following schema:
```
table {
6: quux: required map<7: string, 8: map<9: string, 10: int>>
}
```
This has the following column names:
```python
['quux.value.key', 'quux.value.value', 'quux.key', 'quux.value', 'quux']
```
But we need to set the configuration in line with the PyArrow naming
convention:
```python
{'quux.key_value.key': 7,
'quux.key_value.value': 8,
'quux.value.key_value.key': 9,
'quux.value.key_value.value': 10,
'qux.list.element': 5}
```
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1013,3 +1027,359 @@ def map_key_partner(self, partner_map:
Optional[pa.Array]) -> Optional[pa.Array]
def map_value_partner(self, partner_map: Optional[pa.Array]) ->
Optional[pa.Array]:
return partner_map.items if isinstance(partner_map, pa.MapArray) else
None
+
+
+BOUND_TRUNCATED_LENGHT = 16
+TRUNCATION_EXPR = r"^truncate\((\d+)\)$"
Review Comment:
We can re-use the one from `Transforms.py`:
https://github.com/apache/iceberg/blob/62cb7b5c50451085d6e59f0594292bf883af4220/python/pyiceberg/transforms.py#L100
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1013,3 +1027,359 @@ def map_key_partner(self, partner_map:
Optional[pa.Array]) -> Optional[pa.Array]
def map_value_partner(self, partner_map: Optional[pa.Array]) ->
Optional[pa.Array]:
return partner_map.items if isinstance(partner_map, pa.MapArray) else
None
+
+
+BOUND_TRUNCATED_LENGHT = 16
+TRUNCATION_EXPR = r"^truncate\((\d+)\)$"
+
+logger = logging.getLogger(__name__)
+
+# 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_BOOL.pack(value)
+
+
+def int32_to_avro(value: int) -> bytes:
+ return STRUCT_INT32.pack(value)
+
+
+def int64_to_avro(value: int) -> bytes:
+ return STRUCT_INT64.pack(value)
+
+
+def float_to_avro(value: float) -> bytes:
+ return STRUCT_FLOAT.pack(value)
+
+
+def double_to_avro(value: float) -> bytes:
+ return STRUCT_DOUBLE.pack(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, trunc_length: Optional[int] = None)
-> None:
+ self.current_min: Any = None
+ self.current_max: Any = None
+ self.serialize: Any = None
+ self.trunc_lenght = trunc_length
+
+ 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 self.current_min is None:
+ self.current_min = val
+ else:
+ self.current_min = min(val, self.current_min)
+
+ def add_max(self, val: bytes) -> None:
+ if self.current_max is None:
+ self.current_max = val
+ else:
+ self.current_max = max(self.current_max, val)
+
+ def get_min(self) -> bytes:
+ return self.serialize(self.current_min)[: self.trunc_lenght]
+
+ def get_max(self) -> bytes:
+ return self.serialize(self.current_max)[: self.trunc_lenght]
+
+
+class MetricsMode(Enum):
+ NONE = 0
+ COUNTS = 1
+ TRUNC = 2
Review Comment:
I'm thinking, should we extend this Enum to a frozen data class annotated
with a Singleton? (Similar to the Types itself?)
--
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]