maxdebayser commented on code in PR #7831:
URL: https://github.com/apache/iceberg/pull/7831#discussion_r1261671941
##########
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 couldn't find a lot of good examples of the Java API, so I'm assuming that
the `Schema.find_column_name()` returns a fully qualified column name that is
consistent with the Java API.
--
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]