Fokko commented on code in PR #7831:
URL: https://github.com/apache/iceberg/pull/7831#discussion_r1284501717
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1025,3 +1040,337 @@ 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
+
+
+_PRIMITIVE_TO_PHYSICAL = {
+ BooleanType(): "BOOLEAN",
+ IntegerType(): "INT32",
+ LongType(): "INT64",
+ FloatType(): "FLOAT",
+ DoubleType(): "DOUBLE",
+ DateType(): "INT32",
+ TimeType(): "INT64",
+ TimestampType(): "INT64",
+ TimestamptzType(): "INT64",
+ StringType(): "BYTE_ARRAY",
+ UUIDType(): "FIXED_LEN_BYTE_ARRAY",
+ BinaryType(): "BYTE_ARRAY",
+}
+_PHYSICAL_TYPES = ["BOOLEAN", "INT32", "INT64", "INT96", "FLOAT", "DOUBLE",
"BYTE_ARRAY", "FIXED_LEN_BYTE_ARRAY"]
+
+
+class StatsAggregator:
Review Comment:
```suggestion
class StatsAggregator:
current_min: Any
current_max: Any
trunc_length: Optional[int]
```
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1025,3 +1040,337 @@ 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
+
+
+_PRIMITIVE_TO_PHYSICAL = {
+ BooleanType(): "BOOLEAN",
+ IntegerType(): "INT32",
+ LongType(): "INT64",
+ FloatType(): "FLOAT",
+ DoubleType(): "DOUBLE",
+ DateType(): "INT32",
+ TimeType(): "INT64",
+ TimestampType(): "INT64",
+ TimestamptzType(): "INT64",
+ StringType(): "BYTE_ARRAY",
+ UUIDType(): "FIXED_LEN_BYTE_ARRAY",
+ BinaryType(): "BYTE_ARRAY",
+}
+_PHYSICAL_TYPES = ["BOOLEAN", "INT32", "INT64", "INT96", "FLOAT", "DOUBLE",
"BYTE_ARRAY", "FIXED_LEN_BYTE_ARRAY"]
+
+
+class StatsAggregator:
+ def __init__(self, iceberg_type: PrimitiveType, physical_type_string: str,
trunc_length: Optional[int] = None) -> None:
+ self.current_min: Any = None
+ self.current_max: Any = None
+ self.trunc_length = trunc_length
+
+ if physical_type_string not in _PHYSICAL_TYPES:
+ raise ValueError(f"Unknown physical type {physical_type_string}")
+
+ if physical_type_string == "INT96":
+ raise NotImplementedError("Statistics not implemented for INT96
physical type")
+
+ if _PRIMITIVE_TO_PHYSICAL[iceberg_type] != physical_type_string:
+ raise ValueError(
+ f"Unexpected physical type {physical_type_string} for
{iceberg_type}, expected {_PRIMITIVE_TO_PHYSICAL[iceberg_type]}"
+ )
+
+ self.primitive_type = iceberg_type
+
+ def serialize(self, value: Any) -> bytes:
+ if type(value) == date:
+ value = date_to_days(value)
+ elif type(value) == time:
+ value = time_object_to_micros(value)
+ elif type(value) == datetime:
+ value = datetime_to_micros(value)
+
+ if self.primitive_type == UUIDType():
+ value = uuid.UUID(bytes=value)
+
+ return to_bytes(self.primitive_type, value)
+
+ def add_min(self, val: Any) -> 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: Any) -> None:
+ if self.current_max is None:
+ self.current_max = val
+ else:
+ self.current_max = max(self.current_max, val)
Review Comment:
```suggestion
self.current_max = val if self.current_max is None else max(val,
self.current_max)
```
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1025,3 +1040,337 @@ 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
+
+
+_PRIMITIVE_TO_PHYSICAL = {
+ BooleanType(): "BOOLEAN",
+ IntegerType(): "INT32",
+ LongType(): "INT64",
+ FloatType(): "FLOAT",
+ DoubleType(): "DOUBLE",
+ DateType(): "INT32",
+ TimeType(): "INT64",
+ TimestampType(): "INT64",
+ TimestamptzType(): "INT64",
+ StringType(): "BYTE_ARRAY",
+ UUIDType(): "FIXED_LEN_BYTE_ARRAY",
+ BinaryType(): "BYTE_ARRAY",
+}
+_PHYSICAL_TYPES = ["BOOLEAN", "INT32", "INT64", "INT96", "FLOAT", "DOUBLE",
"BYTE_ARRAY", "FIXED_LEN_BYTE_ARRAY"]
+
+
+class StatsAggregator:
+ def __init__(self, iceberg_type: PrimitiveType, physical_type_string: str,
trunc_length: Optional[int] = None) -> None:
+ self.current_min: Any = None
+ self.current_max: Any = None
+ self.trunc_length = trunc_length
+
+ if physical_type_string not in _PHYSICAL_TYPES:
+ raise ValueError(f"Unknown physical type {physical_type_string}")
+
+ if physical_type_string == "INT96":
+ raise NotImplementedError("Statistics not implemented for INT96
physical type")
+
+ if _PRIMITIVE_TO_PHYSICAL[iceberg_type] != physical_type_string:
+ raise ValueError(
+ f"Unexpected physical type {physical_type_string} for
{iceberg_type}, expected {_PRIMITIVE_TO_PHYSICAL[iceberg_type]}"
+ )
+
+ self.primitive_type = iceberg_type
+
+ def serialize(self, value: Any) -> bytes:
+ if type(value) == date:
+ value = date_to_days(value)
+ elif type(value) == time:
+ value = time_object_to_micros(value)
+ elif type(value) == datetime:
+ value = datetime_to_micros(value)
+
+ if self.primitive_type == UUIDType():
+ value = uuid.UUID(bytes=value)
+
+ return to_bytes(self.primitive_type, value)
+
+ def add_min(self, val: Any) -> None:
+ if self.current_min is None:
+ self.current_min = val
+ else:
+ self.current_min = min(val, self.current_min)
Review Comment:
```suggestion
self.current_min = val if self.current_min is None else min(val,
self.current_min)
```
##########
python/tests/io/test_pyarrow.py:
##########
@@ -1345,3 +1373,659 @@ 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:
+ table_metadata = {
+ "format-version": 2,
+ "location": "s3://bucket/test/location",
+ "last-column-id": 7,
+ "current-schema-id": 0,
+ "schemas": [
+ {
+ "type": "struct",
+ "schema-id": 0,
+ "fields": [
+ {"id": 1, "name": "strings", "required": False, "type":
"string"},
+ {"id": 2, "name": "floats", "required": False, "type":
"float"},
+ {
+ "id": 3,
+ "name": "list",
+ "required": False,
+ "type": {"type": "list", "element-id": 5, "element":
"long", "element-required": False},
+ },
+ {
+ "id": 4,
+ "name": "maps",
+ "required": False,
+ "type": {
+ "type": "map",
+ "key-id": 6,
+ "key": "long",
+ "value-id": 7,
+ "value": "long",
+ "value-required": False,
+ },
+ },
+ ],
+ },
+ ],
+ "default-spec-id": 0,
+ "partition-specs": [{"spec-id": 0, "fields": []}],
+ "properties": {},
+ }
+
+ table_metadata = TableMetadataUtil.parse_obj(table_metadata)
+ arrow_schema = schema_to_pyarrow(table_metadata.schemas[0])
+
+ _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=arrow_schema,
+ )
+ f = pa.BufferOutputStream()
+
+ metadata_collector: List[Any] = []
+ writer = pq.ParquetWriter(f, table.schema,
metadata_collector=metadata_collector)
+
+ writer.write_table(table)
+ writer.close()
Review Comment:
```suggestion
metadata_collector: List[Any] = []
with pa.BufferOutputStream() as f:
with pq.ParquetWriter(f, table.schema,
metadata_collector=metadata_collector) as writer:
writer.write_table(table)
```
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1025,3 +1040,337 @@ 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
+
+
+_PRIMITIVE_TO_PHYSICAL = {
+ BooleanType(): "BOOLEAN",
+ IntegerType(): "INT32",
+ LongType(): "INT64",
+ FloatType(): "FLOAT",
+ DoubleType(): "DOUBLE",
+ DateType(): "INT32",
+ TimeType(): "INT64",
+ TimestampType(): "INT64",
+ TimestamptzType(): "INT64",
+ StringType(): "BYTE_ARRAY",
+ UUIDType(): "FIXED_LEN_BYTE_ARRAY",
+ BinaryType(): "BYTE_ARRAY",
+}
+_PHYSICAL_TYPES = ["BOOLEAN", "INT32", "INT64", "INT96", "FLOAT", "DOUBLE",
"BYTE_ARRAY", "FIXED_LEN_BYTE_ARRAY"]
+
+
+class StatsAggregator:
+ def __init__(self, iceberg_type: PrimitiveType, physical_type_string: str,
trunc_length: Optional[int] = None) -> None:
+ self.current_min: Any = None
+ self.current_max: Any = None
+ self.trunc_length = trunc_length
+
+ if physical_type_string not in _PHYSICAL_TYPES:
+ raise ValueError(f"Unknown physical type {physical_type_string}")
+
+ if physical_type_string == "INT96":
+ raise NotImplementedError("Statistics not implemented for INT96
physical type")
+
+ if _PRIMITIVE_TO_PHYSICAL[iceberg_type] != physical_type_string:
+ raise ValueError(
+ f"Unexpected physical type {physical_type_string} for
{iceberg_type}, expected {_PRIMITIVE_TO_PHYSICAL[iceberg_type]}"
+ )
+
+ self.primitive_type = iceberg_type
+
+ def serialize(self, value: Any) -> bytes:
+ if type(value) == date:
+ value = date_to_days(value)
+ elif type(value) == time:
+ value = time_object_to_micros(value)
+ elif type(value) == datetime:
+ value = datetime_to_micros(value)
+
+ if self.primitive_type == UUIDType():
+ value = uuid.UUID(bytes=value)
+
+ return to_bytes(self.primitive_type, value)
+
+ def add_min(self, val: Any) -> 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: Any) -> 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:
+ if self.primitive_type == StringType():
+ if type(self.current_min) != str:
+ raise ValueError("Expected the current_min to be a string")
+ return self.serialize(self.current_min[: self.trunc_length])
+ else:
+ return self.serialize(self.current_min)[: self.trunc_length]
+
+ def get_max(self) -> Optional[bytes]:
+ if self.primitive_type == StringType():
+ if type(self.current_max) != str:
+ raise ValueError("Expected the current_max to be a string")
+
+ s_result = self.current_max[: self.trunc_length]
+ if s_result != self.current_max:
+ chars = [*s_result]
+
+ for i in range(-1, -len(s_result) - 1, -1):
+ try:
+ to_inc = ord(chars[i])
+ # will raise exception if the highest unicode code is
reached
+ _next = chr(to_inc + 1)
+ chars[i] = _next
+ return self.serialize("".join(chars))
+ except ValueError:
+ pass
+ return None # didn't find a valid upper bound
+ return self.serialize(s_result)
+ elif self.primitive_type == BinaryType():
+ if type(self.current_max) != bytes:
+ raise ValueError("Expected the current_max to be bytes")
+ b_result = self.current_max[: self.trunc_length]
+ if b_result != self.current_max:
+ _bytes = [*b_result]
+ for i in range(-1, -len(b_result) - 1, -1):
+ if _bytes[i] < 255:
+ _bytes[i] += 1
+ return b"".join([i.to_bytes(1, byteorder="little") for
i in _bytes])
+ return None
+
+ return self.serialize(b_result)
+ else:
+ return self.serialize(self.current_max)[: self.trunc_length]
+
+
+DEFAULT_TRUNCATION_LENGHT = 16
Review Comment:
```suggestion
DEFAULT_TRUNCATION_LENGTH = 16
```
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1025,3 +1040,337 @@ 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
+
+
+_PRIMITIVE_TO_PHYSICAL = {
+ BooleanType(): "BOOLEAN",
+ IntegerType(): "INT32",
+ LongType(): "INT64",
+ FloatType(): "FLOAT",
+ DoubleType(): "DOUBLE",
+ DateType(): "INT32",
+ TimeType(): "INT64",
+ TimestampType(): "INT64",
+ TimestamptzType(): "INT64",
+ StringType(): "BYTE_ARRAY",
+ UUIDType(): "FIXED_LEN_BYTE_ARRAY",
+ BinaryType(): "BYTE_ARRAY",
+}
+_PHYSICAL_TYPES = ["BOOLEAN", "INT32", "INT64", "INT96", "FLOAT", "DOUBLE",
"BYTE_ARRAY", "FIXED_LEN_BYTE_ARRAY"]
+
+
+class StatsAggregator:
+ def __init__(self, iceberg_type: PrimitiveType, physical_type_string: str,
trunc_length: Optional[int] = None) -> None:
+ self.current_min: Any = None
+ self.current_max: Any = None
+ self.trunc_length = trunc_length
+
+ if physical_type_string not in _PHYSICAL_TYPES:
+ raise ValueError(f"Unknown physical type {physical_type_string}")
+
+ if physical_type_string == "INT96":
+ raise NotImplementedError("Statistics not implemented for INT96
physical type")
+
+ if _PRIMITIVE_TO_PHYSICAL[iceberg_type] != physical_type_string:
+ raise ValueError(
+ f"Unexpected physical type {physical_type_string} for
{iceberg_type}, expected {_PRIMITIVE_TO_PHYSICAL[iceberg_type]}"
+ )
+
+ self.primitive_type = iceberg_type
+
+ def serialize(self, value: Any) -> bytes:
+ if type(value) == date:
+ value = date_to_days(value)
+ elif type(value) == time:
+ value = time_object_to_micros(value)
+ elif type(value) == datetime:
+ value = datetime_to_micros(value)
+
+ if self.primitive_type == UUIDType():
+ value = uuid.UUID(bytes=value)
+
+ return to_bytes(self.primitive_type, value)
+
+ def add_min(self, val: Any) -> 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: Any) -> 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:
+ if self.primitive_type == StringType():
+ if type(self.current_min) != str:
+ raise ValueError("Expected the current_min to be a string")
+ return self.serialize(self.current_min[: self.trunc_length])
+ else:
+ return self.serialize(self.current_min)[: self.trunc_length]
Review Comment:
```suggestion
return self.serialize(
self.current_min
if self.trunc_length is None
else
TruncateTransform(width=self.trunc_length).transform(self.primitive_type)(self.current_min)
)
```
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1025,3 +1040,291 @@ 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
+
+
+_PRIMITIVE_TO_PHYSICAL = {
+ BooleanType(): "BOOLEAN",
+ IntegerType(): "INT32",
+ LongType(): "INT64",
+ FloatType(): "FLOAT",
+ DoubleType(): "DOUBLE",
+ DateType(): "INT32",
+ TimeType(): "INT64",
+ TimestampType(): "INT64",
+ TimestamptzType(): "INT64",
+ StringType(): "BYTE_ARRAY",
+ UUIDType(): "FIXED_LEN_BYTE_ARRAY",
+ BinaryType(): "BYTE_ARRAY",
+}
+_PHISICAL_TYPES = ["BOOLEAN", "INT32", "INT64", "INT96", "FLOAT", "DOUBLE",
"BYTE_ARRAY", "FIXED_LEN_BYTE_ARRAY"]
+
+
+class StatsAggregator:
+ def __init__(self, iceberg_type: PrimitiveType, physical_type_string: str,
trunc_length: Optional[int] = None) -> None:
+ self.current_min: Any = None
+ self.current_max: Any = None
+ self.trunc_length = trunc_length
+
+ assert physical_type_string in _PHISICAL_TYPES, f"Unknown physical
type {physical_type_string}"
+ if physical_type_string == "INT96":
+ raise NotImplementedError("Statistics not implemented for INT96
physical type")
+ assert (
+ _PRIMITIVE_TO_PHYSICAL[iceberg_type] == physical_type_string
+ ), f"Unexpected physical type {physical_type_string} for
{iceberg_type}, expected {_PRIMITIVE_TO_PHYSICAL[iceberg_type]}"
+
+ self.primitive_type = iceberg_type
+
+ def serialize(self, value: Any) -> bytes:
+ if type(value) == date:
Review Comment:
The PR is in :)
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1025,3 +1040,337 @@ 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
+
+
+_PRIMITIVE_TO_PHYSICAL = {
+ BooleanType(): "BOOLEAN",
+ IntegerType(): "INT32",
+ LongType(): "INT64",
+ FloatType(): "FLOAT",
+ DoubleType(): "DOUBLE",
+ DateType(): "INT32",
+ TimeType(): "INT64",
+ TimestampType(): "INT64",
+ TimestamptzType(): "INT64",
+ StringType(): "BYTE_ARRAY",
+ UUIDType(): "FIXED_LEN_BYTE_ARRAY",
+ BinaryType(): "BYTE_ARRAY",
+}
+_PHYSICAL_TYPES = ["BOOLEAN", "INT32", "INT64", "INT96", "FLOAT", "DOUBLE",
"BYTE_ARRAY", "FIXED_LEN_BYTE_ARRAY"]
+
+
+class StatsAggregator:
+ def __init__(self, iceberg_type: PrimitiveType, physical_type_string: str,
trunc_length: Optional[int] = None) -> None:
+ self.current_min: Any = None
+ self.current_max: Any = None
+ self.trunc_length = trunc_length
+
+ if physical_type_string not in _PHYSICAL_TYPES:
+ raise ValueError(f"Unknown physical type {physical_type_string}")
+
+ if physical_type_string == "INT96":
+ raise NotImplementedError("Statistics not implemented for INT96
physical type")
+
+ if _PRIMITIVE_TO_PHYSICAL[iceberg_type] != physical_type_string:
+ raise ValueError(
+ f"Unexpected physical type {physical_type_string} for
{iceberg_type}, expected {_PRIMITIVE_TO_PHYSICAL[iceberg_type]}"
+ )
+
+ self.primitive_type = iceberg_type
+
+ def serialize(self, value: Any) -> bytes:
+ if type(value) == date:
+ value = date_to_days(value)
+ elif type(value) == time:
+ value = time_object_to_micros(value)
+ elif type(value) == datetime:
+ value = datetime_to_micros(value)
+
+ if self.primitive_type == UUIDType():
+ value = uuid.UUID(bytes=value)
+
+ return to_bytes(self.primitive_type, value)
+
+ def add_min(self, val: Any) -> 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: Any) -> 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:
+ if self.primitive_type == StringType():
+ if type(self.current_min) != str:
+ raise ValueError("Expected the current_min to be a string")
+ return self.serialize(self.current_min[: self.trunc_length])
+ else:
+ return self.serialize(self.current_min)[: self.trunc_length]
+
+ def get_max(self) -> Optional[bytes]:
+ if self.primitive_type == StringType():
+ if type(self.current_max) != str:
+ raise ValueError("Expected the current_max to be a string")
+
+ s_result = self.current_max[: self.trunc_length]
+ if s_result != self.current_max:
+ chars = [*s_result]
+
+ for i in range(-1, -len(s_result) - 1, -1):
+ try:
+ to_inc = ord(chars[i])
+ # will raise exception if the highest unicode code is
reached
+ _next = chr(to_inc + 1)
+ chars[i] = _next
+ return self.serialize("".join(chars))
+ except ValueError:
+ pass
+ return None # didn't find a valid upper bound
+ return self.serialize(s_result)
+ elif self.primitive_type == BinaryType():
+ if type(self.current_max) != bytes:
+ raise ValueError("Expected the current_max to be bytes")
+ b_result = self.current_max[: self.trunc_length]
+ if b_result != self.current_max:
+ _bytes = [*b_result]
+ for i in range(-1, -len(b_result) - 1, -1):
+ if _bytes[i] < 255:
+ _bytes[i] += 1
+ return b"".join([i.to_bytes(1, byteorder="little") for
i in _bytes])
+ return None
+
+ return self.serialize(b_result)
+ else:
+ return self.serialize(self.current_max)[: self.trunc_length]
+
+
+DEFAULT_TRUNCATION_LENGHT = 16
+TRUNCATION_EXPR = r"^truncate\((\d+)\)$"
+
+
+class MetricModeTypes(Enum):
+ TRUNCATE = "truncate"
+ NONE = "none"
+ COUNTS = "counts"
+ FULL = "full"
+
+
+DEFAULT_METRICS_MODE_KEY = "write.metadata.metrics.default"
+COLUMN_METRICS_MODE_KEY_PREFIX = "write.metadata.metrics.column"
+
+
+@dataclass(frozen=True)
+class MetricsMode(Singleton):
+ type: MetricModeTypes
+ length: Optional[int] = None
+
+
+def match_metrics_mode(mode: str) -> MetricsMode:
+ m = re.match(TRUNCATION_EXPR, mode, re.IGNORECASE)
+ if m:
+ length = int(m[1])
+ if length < 1:
+ raise ValueError("Truncation length must be larger than 0")
+ return MetricsMode(MetricModeTypes.TRUNCATE, int(m[1]))
+ elif re.match("^none$", mode, re.IGNORECASE):
+ return MetricsMode(MetricModeTypes.NONE)
+ elif re.match("^counts$", mode, re.IGNORECASE):
+ return MetricsMode(MetricModeTypes.COUNTS)
+ elif re.match("^full$", mode, re.IGNORECASE):
+ return MetricsMode(MetricModeTypes.FULL)
+ else:
+ raise ValueError(f"Unsupported metrics mode {mode}")
+
+
+@dataclass(frozen=True)
+class StatisticsCollector:
+ field_id: int
+ iceberg_type: PrimitiveType
+ mode: MetricsMode
+ column_name: str
+
+
+class
PyArrowStatisticsCollector(PreOrderSchemaVisitor[List[StatisticsCollector]]):
+ _field_id = 0
+ _schema: Schema
+ _properties: Dict[str, str]
+
+ 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]:
+ column_name = self._schema.find_column_name(self._field_id)
+ if column_name is None:
+ raise ValueError(f"Column for field {self._field_id} not found")
+
+ metrics_mode = MetricsMode(MetricModeTypes.TRUNCATE,
DEFAULT_TRUNCATION_LENGHT)
Review Comment:
```suggestion
metrics_mode = MetricsMode(MetricModeTypes.TRUNCATE,
DEFAULT_TRUNCATION_LENGTH)
```
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1025,3 +1040,337 @@ 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
+
+
+_PRIMITIVE_TO_PHYSICAL = {
+ BooleanType(): "BOOLEAN",
+ IntegerType(): "INT32",
+ LongType(): "INT64",
+ FloatType(): "FLOAT",
+ DoubleType(): "DOUBLE",
+ DateType(): "INT32",
+ TimeType(): "INT64",
+ TimestampType(): "INT64",
+ TimestamptzType(): "INT64",
+ StringType(): "BYTE_ARRAY",
+ UUIDType(): "FIXED_LEN_BYTE_ARRAY",
+ BinaryType(): "BYTE_ARRAY",
+}
+_PHYSICAL_TYPES = ["BOOLEAN", "INT32", "INT64", "INT96", "FLOAT", "DOUBLE",
"BYTE_ARRAY", "FIXED_LEN_BYTE_ARRAY"]
Review Comment:
```suggestion
_PHYSICAL_TYPES = set(_PRIMITIVE_TO_PHYSICAL.values())
```
--
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]