maxdebayser commented on code in PR #7831:
URL: https://github.com/apache/iceberg/pull/7831#discussion_r1286009490
##########
python/pyiceberg/io/pyarrow.py:
##########
@@ -1025,3 +1039,335 @@ 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 = set(_PRIMITIVE_TO_PHYSICAL.values()).union({"INT96"})
+
+
+class StatsAggregator:
+ current_min: Any
+ current_max: Any
+ trunc_length: Optional[int]
+
+ def __init__(self, iceberg_type: PrimitiveType, physical_type_string: str,
trunc_length: Optional[int] = None) -> None:
+ self.current_min = None
+ self.current_max = 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")
+
+ expected_physical_type = _PRIMITIVE_TO_PHYSICAL[iceberg_type]
+ if expected_physical_type != physical_type_string:
+ raise ValueError(
+ f"Unexpected physical type {physical_type_string} for
{iceberg_type}, expected {expected_physical_type}"
+ )
+
+ self.primitive_type = iceberg_type
+
+ def serialize(self, value: Any) -> bytes:
+ if self.primitive_type == UUIDType():
+ value = uuid.UUID(bytes=value)
+
+ return to_bytes(self.primitive_type, value)
+
+ def add_min(self, val: Any) -> None:
+ self.current_min = val if self.current_min is None else min(val,
self.current_min)
+
+ def add_max(self, val: Any) -> None:
+ self.current_max = val if self.current_max is None else max(val,
self.current_max)
+
+ def get_min(self) -> bytes:
+ 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)
+ )
+
+ def get_max(self) -> Optional[bytes]:
+ if self.current_max is None:
+ return None
+
+ 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_LENGTH = 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:
+ sanitized_mode = mode.lower()
+ if sanitized_mode.startswith("truncate"):
+ 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]))
+ else:
+ raise ValueError(f"Malformed truncate: {mode}")
+ elif sanitized_mode.startswith("none"):
Review Comment:
It didn't, it's an artifact of the review process. The first version of the
code matched beginning and end of the string:
```
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}")
```
--
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]