You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by GitBox <gi...@apache.org> on 2022/01/10 18:28:09 UTC

[GitHub] [iceberg] rdblue commented on a change in pull request #3450: [Python] support iceberg transforms in python

rdblue commented on a change in pull request #3450:
URL: https://github.com/apache/iceberg/pull/3450#discussion_r781445687



##########
File path: python/src/iceberg/transforms.py
##########
@@ -0,0 +1,471 @@
+# 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 re
+import struct
+from typing import Any, Callable, Optional
+
+import mmh3  # type: ignore
+
+from iceberg.types import (
+    BinaryType,
+    DateType,
+    DecimalType,
+    DoubleType,
+    FixedType,
+    FloatType,
+    IntegerType,
+    LongType,
+    StringType,
+    TimestampType,
+    TimestamptzType,
+    TimeType,
+    Type,
+    UUIDType,
+)
+from iceberg.utils import transform_util
+
+
+class Transform:
+    """Transform base class for concrete transforms.
+
+    A base class to transform values and project predicates on partition values.
+    This class is not used directly. Instead, use one of module method to create the child classes.
+
+    Args:
+        transform_string (str): name of the transform type
+        repr_string (str): string representation of a transform instance
+        to_human_str (callable, optional): A function that returns the human-readable string
+          given a value. By default, the built-in `str` method is used.
+    """
+
+    def __init__(
+        self,
+        transform_string: str,
+        repr_string: str,
+        to_human_str: Callable[[Any], str] = str,
+    ):
+        self._transform_string = transform_string
+        self._repr_string = repr_string
+        self._to_human_string = to_human_str
+
+    def __repr__(self):
+        return self._repr_string
+
+    def __str__(self):
+        return self._transform_string
+
+    def apply(self, value):
+        raise NotImplementedError()
+
+    def can_transform(self, target: Type) -> bool:
+        return False
+
+    def result_type(self, source: Type) -> Type:
+        return source
+
+    def preserves_order(self) -> bool:
+        return False
+
+    def satisfies_order_of(self, other) -> bool:
+        return self == other
+
+    def to_human_string(self, value) -> str:
+        if value is None:
+            return "null"
+        return self._to_human_string(value)
+
+    def dedup_name(self) -> str:
+        return self._transform_string
+
+
+class Bucket(Transform):
+    """Transforms a value into a bucket partition value
+
+    Transforms are parameterized by a number of buckets. Bucket partition transforms use a 32-bit
+    hash of the source value to produce a positive value by mod the bucket number.
+
+    Args:
+      source_type (Type): An Iceberg Type of IntegerType, LongType, DecimalType, DateType, TimeType,
+      TimestampType, TimestamptzType, StringType, BinaryType, UUIDType, FloatType, or DoubleType.
+      num_buckets (int): The number of buckets.
+
+    Raises:
+      ValueError: If a type is provided that is incompatible with a Bucket transform
+    """
+
+    _MAX_32_BITS_INT = 2147483647
+    _INT_TRANSFORMABLE_TYPES = {
+        IntegerType,
+        DateType,
+        LongType,
+        TimeType,
+        TimestampType,
+        TimestamptzType,
+    }
+    _SAME_TRANSFORMABLE_TYPES = {
+        StringType,
+        BinaryType,
+        UUIDType,
+        FloatType,
+        DoubleType,
+    }
+
+    def __init__(self, source_type: Type, num_buckets: int):
+        super().__init__(
+            f"bucket[{num_buckets}]",
+            f"transforms.bucket(source_type={repr(source_type)}, num_buckets={num_buckets})",
+        )
+        self._type = source_type
+        self._num_buckets = num_buckets
+
+        if isinstance(self._type, FixedType) or isinstance(self._type, DecimalType):
+            self._can_transform = lambda t: type(self._type) is type(t)
+        elif self._type in Bucket._SAME_TRANSFORMABLE_TYPES:
+            self._can_transform = lambda t: self._type == t
+        elif self._type in Bucket._INT_TRANSFORMABLE_TYPES:
+            self._can_transform = (
+                lambda t: self._type in Bucket._INT_TRANSFORMABLE_TYPES
+            )
+        else:
+            raise ValueError(f"Cannot bucket by type: {source_type}")
+
+        if (
+            isinstance(self._type, FixedType)
+            or self._type == StringType
+            or self._type == BinaryType
+        ):
+            self._hash_func = lambda v: mmh3.hash(v)
+        elif isinstance(self._type, DecimalType):
+            self._hash_func = lambda v: mmh3.hash(transform_util.decimal_to_bytes(v))
+        elif self._type == FloatType or self._type == DoubleType:
+            # bucketing by Float/Double is not allowed by the spec, but they have hash implementation
+            self._hash_func = lambda v: mmh3.hash(struct.pack("d", v))
+        elif self._type == UUIDType:
+            self._hash_func = lambda v: mmh3.hash(
+                struct.pack(
+                    ">QQ",
+                    (v.int >> 64) & 0xFFFFFFFFFFFFFFFF,
+                    v.int & 0xFFFFFFFFFFFFFFFF,
+                )
+            )
+        else:
+            self._hash_func = lambda v: mmh3.hash(struct.pack("q", v))
+
+    @property
+    def num_buckets(self) -> int:
+        return self._num_buckets
+
+    def apply(self, value) -> Optional[int]:
+        if value is None:
+            return None
+
+        return (self._hash_func(value) & Bucket._MAX_32_BITS_INT) % self._num_buckets
+
+    def can_transform(self, target: Type) -> bool:
+        return self._can_transform(target)
+
+    def result_type(self, source: Type):
+        return IntegerType
+
+
+class TimeTransform(Transform):
+    """Time class is for both Date transforms and Timestamp transforms."""
+
+    _TIME_SATISFIED_ORDER = dict(year=3, month=2, day=1, hour=0)
+
+    def __init__(self, source_type: Type, name: str, apply_func: Callable[[int], int]):
+        super().__init__(
+            name,
+            f"transforms.{name}(source_type={repr(source_type)})",
+            getattr(transform_util, f"human_{name}"),
+        )
+        self._type = source_type
+        self._name = name
+        self._apply = apply_func
+        self._result_type = DateType if self._name == "day" else IntegerType
+
+    def apply(self, value: int) -> int:
+        return self._apply(value)
+
+    def can_transform(self, target: Type) -> bool:
+        if self._type == DateType:
+            return target == DateType
+        else:  # self._type is either TimestampType or TimestamptzType
+            return target == TimestampType or target == TimestamptzType
+
+    def result_type(self, source_type: Type) -> Type:
+        return self._result_type
+
+    def preserves_order(self) -> bool:
+        return True
+
+    def satisfies_order_of(self, other: Transform) -> bool:
+        if self == other:
+            return True
+
+        if isinstance(other, TimeTransform):
+            return (
+                TimeTransform._TIME_SATISFIED_ORDER[self._name]
+                <= TimeTransform._TIME_SATISFIED_ORDER[other._name]
+            )
+
+        return False
+
+    def dedup_name(self) -> str:
+        return "time"
+
+
+class Identity(Transform):
+    def __init__(
+        self,
+        source_type: Type,
+        human_str: Callable[[Any], str],
+    ):
+        super().__init__(
+            "identity",
+            f"transforms.identity(source_type={repr(source_type)})",
+            human_str,
+        )
+        self._type = source_type
+
+    def apply(self, value):
+        return value
+
+    def can_transform(self, target: Type) -> bool:
+        return target.is_primitive
+
+    def preserves_order(self) -> bool:
+        return True
+
+    def satisfies_order_of(self, other: Transform) -> bool:
+        return other.preserves_order()
+
+
+class Truncate(Transform):
+    """A transform for truncating a value to a specified width.
+
+    Args:
+      source_type (Type): An Iceberg Type of IntegerType, LongType, StringType, or BinaryType
+      width (int): The truncate width
+
+    Raises:
+      ValueError: If a type is provided that is incompatible with a Truncate transform
+    """
+
+    _VALID_TYPES = {IntegerType, LongType, StringType, BinaryType}
+    _TO_HUMAN_STR = {BinaryType: transform_util.base64encode}
+
+    def __init__(self, source_type: Type, width: int):
+        if source_type not in Truncate._VALID_TYPES and not isinstance(
+            source_type, DecimalType
+        ):
+            raise ValueError(f"Cannot truncate type: {source_type}")
+
+        super().__init__(
+            f"truncate[{width}]",
+            f"transforms.truncate(source_type={repr(source_type)}, width={width})",
+            Truncate._TO_HUMAN_STR.get(source_type, str),
+        )
+        self._type = source_type
+        self._width = width
+
+        if self._type == IntegerType or self._type == LongType:
+            self._apply = lambda v, w: v - v % w
+        elif self._type == StringType or self._type == BinaryType:
+            self._apply = lambda v, w: v[0 : min(w, len(v))]
+        else:  # decimal case
+            self._apply = transform_util.truncate_decimal
+
+    @property
+    def width(self):
+        return self._width
+
+    def apply(self, value):
+        if value is None:
+            return None
+        return self._apply(value, self._width)
+
+    def can_transform(self, target: Type) -> bool:
+        return self._type == target
+
+    def preserves_order(self) -> bool:
+        return True
+
+    def satisfies_order_of(self, other: Transform) -> bool:
+        if self == other:
+            return True
+        elif (
+            StringType == self._type
+            and isinstance(other, Truncate)
+            and StringType == other._type
+        ):
+            return self._width >= other._width
+
+        return False
+
+
+class UnknownTransform(Transform):
+    """A transform that represents when an unknown transform is provided
+
+    Args:
+      source_type (Type): An Iceberg `Type`
+      transform (str): A string name of a transform
+
+    Raises:
+      AttributeError: If the apply method is called.
+    """
+
+    def __init__(self, source_type: Type, transform: str):
+        super().__init__(
+            transform,
+            f"UnknownTransform(source_type={repr(source_type)}, transform={repr(transform)})",
+        )
+        self._type = source_type
+        self._transform = transform
+
+    def apply(self, value):
+        raise AttributeError(f"Cannot apply unsupported transform: {self.__str__()}")

Review comment:
       Is `__str__` not called automatically with string interpolation? Also, why use the `__str__` method rather than calling `str(self)`?




-- 
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: issues-unsubscribe@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org