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/06/23 13:22:21 UTC
[GitHub] [iceberg] Fokko opened a new pull request, #5124: Python: Add sort order fields
Fokko opened a new pull request, #5124:
URL: https://github.com/apache/iceberg/pull/5124
This is required when we start (de)serializing the TableMetadata from the REST catalog.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912526718
##########
python/pyiceberg/table/metadata.py:
##########
@@ -270,7 +271,7 @@ def set_sort_orders(cls, data: Dict[str, Any]):
# This is going to be much nicer as soon as sort-order is an actual pydantic object
# Probably we'll just create a UNSORTED_ORDER constant then
Review Comment:
I'll remove this right away, thanks for the sharp eye @kbendick
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918346523
##########
python/pyiceberg/transforms.py:
##########
@@ -64,11 +72,32 @@ class Transform(IcebergBaseModel, ABC, Generic[S, T]):
__root__: str = Field()
- def __call__(self, value: Optional[S]) -> Optional[T]:
- return self.apply(value)
+ @classmethod
+ def __get_validators__(cls):
+ # one or more validators may be yielded which will be called in the
+ # order to validate the input, each validator will receive as an input
+ # the value returned from the previous validator
+ yield cls.validate
+
+ @classmethod
+ def validate(cls, v: Any):
+ # When Pydantic is unable to determine the subtype
+ # In this case we'll help pydantic a bit by parsing the transform type ourselves
+ if isinstance(v, str):
+ if v == IDENTITY:
+ return IdentityTransform()
+ elif v == VOID:
+ return VoidTransform()
+ elif v.startswith(BUCKET):
+ return BucketTransform(num_buckets=BUCKET_PARSER.match(v))
+ elif v.startswith(TRUNCATE):
+ return TruncateTransform(width=BUCKET_PARSER.match(v))
+ else:
+ return UnknownTransform(transform=v)
+ return v
@abstractmethod
- def apply(self, value: Optional[S]) -> Optional[T]:
+ def hash_function(self, source: IcebergType) -> Callable[[Optional[S]], Optional[T]]:
Review Comment:
While `hash_function` makes sense for the bucket transform, I think we want a more generic name for the base class. What about `transformer`? That way a `Transform` is generic and `transformer` is specific to a type.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918041548
##########
python/pyiceberg/transforms.py:
##########
@@ -64,6 +70,31 @@ class Transform(IcebergBaseModel, ABC, Generic[S, T]):
__root__: str = Field()
+ @classmethod
+ def __get_validators__(cls):
+ # one or more validators may be yielded which will be called in the
+ # order to validate the input, each validator will receive as an input
+ # the value returned from the previous validator
+ yield cls.validate
+
+ @classmethod
+ def validate(cls, v: Any):
+ # When Pydantic is unable to determine the subtype
+ # In this case we'll help pydantic a bit by parsing the transform type ourselves
+ if isinstance(v, str):
+ if v == "identity":
+ bind_func = identity
+ elif v == "void":
+ bind_func = always_null # type: ignore
+ elif v.startswith("bucket"):
+ bind_func = functools.partial(bucket, num_buckets=BaseBucketTransform.parse(v))
Review Comment:
Good point. I was in doubt when writing this if I should create a separate parser for `prefix[int]` patterns, and I just did this. This removes the `.parse` methods which are very similar anyway. Also refactored `fixed[int]` to use the new parser.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r917460146
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,133 @@
+# 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.
+# pylint: disable=keyword-arg-before-vararg
+
+from enum import Enum
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ List,
+ Optional,
+ Union,
+)
+
+from pydantic import Field, root_validator
+
+from pyiceberg.schema import Schema
+from pyiceberg.transforms import Transform, UnboundTransform
+from pyiceberg.types import IcebergType
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ """A field that provides information on how the table is sorted
+
+ Args:
+ source_id (int): Source column id from the table’s schema
+ transform (str): Transform that is used to produce values to be sorted on from the source column.
+ This is the same transform as described in partition transforms.
+ source_id (SortDirection): Sort direction, that can only be either asc or desc
+ source_id (NullOrder): Null order that describes the order of null values when sorted. Can only be either nulls-first or nulls-last
+ """
+
+ class Config:
+ frozen = False
+
+ def __init__(
+ self,
+ source_id: Optional[int] = None,
+ transform: Optional[Union[Transform, Callable[[IcebergType], Transform]]] = None,
+ direction: Optional[SortDirection] = None,
+ null_order: Optional[NullOrder] = None,
+ **data: Any,
+ ):
+ if source_id is not None:
+ data["source-id"] = source_id
+ if transform is not None:
+ data["transform"] = transform
+ if direction is not None:
+ data["direction"] = direction
+ if null_order is not None:
+ data["null-order"] = null_order
+ super().__init__(**data)
+
+ @root_validator(pre=True)
+ def set_null_order(cls, values: Dict[str, Any]) -> Dict[str, Any]:
+ values["direction"] = values["direction"] if values.get("direction") else SortDirection.ASC
Review Comment:
This doesn't need to produce a `str` value? (Assuming since the type is `Any` it works, but this is unexpected for me)
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918318809
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,133 @@
+# 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.
+# pylint: disable=keyword-arg-before-vararg
+from enum import Enum
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ List,
+ Optional,
+ Union,
+)
+
+from pydantic import Field, root_validator
+
+from pyiceberg.schema import Schema
+from pyiceberg.transforms import Transform, UnboundTransform
+from pyiceberg.types import IcebergType
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ """Sort order field
+
+ Args:
+ source_id (int): Source column id from the table’s schema
+ transform (str): Transform that is used to produce values to be sorted on from the source column.
+ This is the same transform as described in partition transforms.
+ direction (SortDirection): Sort direction, that can only be either asc or desc
+ null_order (NullOrder): Null order that describes the order of null values when sorted. Can only be either nulls-first or nulls-last
+ """
+
+ def __init__(
+ self,
+ source_id: Optional[int] = None,
+ transform: Optional[Union[Transform, Callable[[IcebergType], Transform]]] = None,
+ direction: Optional[SortDirection] = None,
+ null_order: Optional[NullOrder] = None,
+ **data: Any,
+ ):
+ if source_id is not None:
+ data["source-id"] = source_id
+ if transform is not None:
+ data["transform"] = transform
+ if direction is not None:
+ data["direction"] = direction
+ if null_order is not None:
+ data["null-order"] = null_order
+ super().__init__(**data)
+
+ @root_validator(pre=True)
+ def set_null_order(cls, values: Dict[str, Any]) -> Dict[str, Any]:
+ values["direction"] = values["direction"] if values.get("direction") else SortDirection.ASC
+ if not values.get("null-order"):
+ values["null-order"] = NullOrder.NULLS_FIRST if values["direction"] == SortDirection.ASC else NullOrder.NULLS_LAST
+ return values
+
+ source_id: int = Field(alias="source-id")
+ transform: Transform = Field()
+ direction: SortDirection = Field()
+ null_order: NullOrder = Field(alias="null-order")
+
+ def bind(self, schema: Schema) -> "SortField":
+ return SortField(
+ source_id=self.source_id,
+ transform=(
+ self.transform.bind(schema.find_type(self.source_id))
+ if isinstance(self.transform, UnboundTransform)
Review Comment:
Good call, but this will be obsolete as well with just passing down the hashing functions.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r917459933
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,133 @@
+# 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.
+# pylint: disable=keyword-arg-before-vararg
+
+from enum import Enum
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ List,
+ Optional,
+ Union,
+)
+
+from pydantic import Field, root_validator
+
+from pyiceberg.schema import Schema
+from pyiceberg.transforms import Transform, UnboundTransform
+from pyiceberg.types import IcebergType
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ """A field that provides information on how the table is sorted
+
+ Args:
+ source_id (int): Source column id from the table’s schema
+ transform (str): Transform that is used to produce values to be sorted on from the source column.
+ This is the same transform as described in partition transforms.
+ source_id (SortDirection): Sort direction, that can only be either asc or desc
Review Comment:
Should be `direction` and `null_order`
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r917461006
##########
python/pyiceberg/transforms.py:
##########
@@ -64,6 +70,31 @@ class Transform(IcebergBaseModel, ABC, Generic[S, T]):
__root__: str = Field()
+ @classmethod
+ def __get_validators__(cls):
+ # one or more validators may be yielded which will be called in the
+ # order to validate the input, each validator will receive as an input
+ # the value returned from the previous validator
+ yield cls.validate
+
+ @classmethod
+ def validate(cls, v: Any):
+ # When Pydantic is unable to determine the subtype
+ # In this case we'll help pydantic a bit by parsing the transform type ourselves
+ if isinstance(v, str):
+ if v == "identity":
+ bind_func = identity
+ elif v == "void":
+ bind_func = always_null # type: ignore
+ elif v.startswith("bucket"):
+ bind_func = functools.partial(bucket, num_buckets=BaseBucketTransform.parse(v))
Review Comment:
In types.py, `parse` is used to return an instance of the type, not to parse part of the string form:
```python
FixedType.parse("fixed[16]") // -> FixedType(length=16)
```
If possible, I'd keep the expectations for those methods the same and return a `BucketTransform` from `BucketTransform.parse`.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912498711
##########
python/tests/table/test_sorting.py:
##########
@@ -0,0 +1,53 @@
+# 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.
+from pyiceberg import transforms
+from pyiceberg.table.sorting import (
+ NullOrder,
+ SortDirection,
+ SortField,
+ SortOrder,
+)
+from pyiceberg.transforms import IdentityTransform
+from pyiceberg.types import IntegerType, StringType
+
+
+def test_serialize_sort_order():
Review Comment:
I still need to implement that one, mostly because of the transform. `bucket[4]` cannot be deserialized to the implementation without knowing which type the source-id refers to.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912060883
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,84 @@
+# 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.
+from enum import Enum
+from typing import Any, List, Optional
+
+from pydantic import Field
+
+from pyiceberg.transforms import Transform
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(str, Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(str, Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ def __init__(
+ self,
+ source_id: int,
+ transform: Transform,
+ direction: SortDirection = SortDirection.ASC,
+ null_order: NullOrder = NullOrder.NULLS_LAST,
+ **data: Any,
+ ):
+ data["source-id"] = source_id
+ data["transform"] = transform
+ data["direction"] = direction
+ data["null-order"] = null_order
+ super().__init__(**data)
+
+ source_id: int = Field(alias="source-id")
+ transform: Transform = Field()
+ direction: SortDirection = Field()
+ null_order: NullOrder = Field(alias="null-order")
+
+
+class SortOrder(IcebergBaseModel):
+ """
+ Users can sort their data within partitions by columns to gain performance.
+ The information on how the data is sorted can be declared per data or delete file, by a sort order.
Review Comment:
This is used for tables and for data/delete files, so I would probably remove this statement.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912061805
##########
python/tests/table/test_sorting.py:
##########
@@ -0,0 +1,53 @@
+# 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.
+from pyiceberg import transforms
+from pyiceberg.table.sorting import (
+ NullOrder,
+ SortDirection,
+ SortField,
+ SortOrder,
+)
+from pyiceberg.transforms import IdentityTransform
+from pyiceberg.types import IntegerType, StringType
+
+
+def test_serialize_sort_order():
Review Comment:
Does deserialization also work?
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918360957
##########
python/pyiceberg/transforms.py:
##########
@@ -130,99 +161,58 @@ def apply(self, value: Optional[S]) -> Optional[int]:
def result_type(self, source: IcebergType) -> IcebergType:
return IntegerType()
- @abstractmethod
- def can_transform(self, source: IcebergType) -> bool:
- pass
-
- def __repr__(self) -> str:
- return f"transforms.bucket(source_type={repr(self._source_type)}, num_buckets={self._num_buckets})"
-
-
-class BucketNumberTransform(BaseBucketTransform):
- """Transforms a value of IntegerType, LongType, DateType, TimeType, TimestampType, or TimestamptzType
- into a bucket partition value
-
- Example:
- >>> transform = BucketNumberTransform(LongType(), 100)
- >>> transform.apply(81068000000)
- 59
- """
-
def can_transform(self, source: IcebergType) -> bool:
- return type(source) in {IntegerType, DateType, LongType, TimeType, TimestampType, TimestamptzType}
-
- def hash(self, value) -> int:
- return mmh3.hash(struct.pack("<q", value))
-
-
-class BucketDecimalTransform(BaseBucketTransform):
- """Transforms a value of DecimalType into a bucket partition value.
-
- Example:
- >>> transform = BucketDecimalTransform(DecimalType(9, 2), 100)
- >>> transform.apply(Decimal("14.20"))
- 59
- """
-
- def can_transform(self, source: IcebergType) -> bool:
- return isinstance(source, DecimalType)
-
- def hash(self, value: Decimal) -> int:
- return mmh3.hash(decimal_to_bytes(value))
-
-
-class BucketStringTransform(BaseBucketTransform):
- """Transforms a value of StringType into a bucket partition value.
-
- Example:
- >>> transform = BucketStringTransform(StringType(), 100)
- >>> transform.apply("iceberg")
- 89
- """
-
- def can_transform(self, source: IcebergType) -> bool:
- return isinstance(source, StringType)
-
- def hash(self, value: str) -> int:
- return mmh3.hash(value)
-
-
-class BucketBytesTransform(BaseBucketTransform):
- """Transforms a value of FixedType or BinaryType into a bucket partition value.
-
- Example:
- >>> transform = BucketBytesTransform(BinaryType(), 100)
- >>> transform.apply(b"\\x00\\x01\\x02\\x03")
- 41
- """
-
- def can_transform(self, source: IcebergType) -> bool:
- return type(source) in {FixedType, BinaryType}
-
- def hash(self, value: bytes) -> int:
- return mmh3.hash(value)
+ return type(source) in {
+ IntegerType,
+ DateType,
+ LongType,
+ TimeType,
+ TimestampType,
+ TimestamptzType,
+ DecimalType,
+ StringType,
+ FixedType,
+ BinaryType,
+ UUIDType,
+ }
+
+ def hash_function(self, source: IcebergType, bucket: bool = True) -> Callable[[Optional[Any]], Optional[int]]:
+ source_type = type(source)
+ if source_type in {IntegerType, LongType, DateType, TimeType, TimestampType, TimestamptzType}:
+
+ def hash_func(v):
+ return mmh3.hash(struct.pack("<q", v))
+
+ elif source_type == DecimalType:
+
+ def hash_func(v):
+ return mmh3.hash(decimal_to_bytes(v))
+
+ elif source_type in {StringType, FixedType, BinaryType}:
+
+ def hash_func(v):
+ return mmh3.hash(v)
+
+ elif source_type == UUIDType:
+
+ def hash_func(v):
Review Comment:
We re-create the functions each time we call the `transform()` method. We could also define them top-level, but then we define a lot of functions in module scope that we don't use all the time. This might consume a bit more memory but shouldn't burn any more CPU cycles.
##########
python/pyiceberg/transforms.py:
##########
@@ -312,6 +293,28 @@ def source_type(self) -> IcebergType:
def width(self) -> int:
return self._width
+ def hash_function(self, source: IcebergType) -> Callable[[Optional[S]], Optional[S]]:
+ source_type = type(source)
+ if source_type in {IntegerType, LongType}:
+
+ def truncate_func(v):
+ return v - v % self._width
+
+ elif source_type in {StringType, BinaryType}:
+
+ def truncate_func(v):
+ return v[0 : min(self._width, len(v))]
Review Comment:
Yes, like it a lot
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912498380
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,84 @@
+# 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.
+from enum import Enum
+from typing import Any, List, Optional
+
+from pydantic import Field
+
+from pyiceberg.transforms import Transform
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(str, Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(str, Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ def __init__(
+ self,
+ source_id: int,
+ transform: Transform,
+ direction: SortDirection = SortDirection.ASC,
+ null_order: NullOrder = NullOrder.NULLS_LAST,
+ **data: Any,
+ ):
+ data["source-id"] = source_id
+ data["transform"] = transform
+ data["direction"] = direction
+ data["null-order"] = null_order
+ super().__init__(**data)
+
+ source_id: int = Field(alias="source-id")
+ transform: Transform = Field()
+ direction: SortDirection = Field()
+ null_order: NullOrder = Field(alias="null-order")
+
+
+class SortOrder(IcebergBaseModel):
+ """
+ Users can sort their data within partitions by columns to gain performance.
+ The information on how the data is sorted can be declared per data or delete file, by a sort order.
Review Comment:
Done!
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918106533
##########
python/pyiceberg/transforms.py:
##########
@@ -96,6 +127,38 @@ def dedup_name(self) -> str:
def __str__(self) -> str:
return self.__root__
+ def __eq__(self, other: Any) -> bool:
+ if isinstance(other, Transform):
+ return self.__root__ == other.__root__
+ return False
+
+
+class UnboundTransform(Transform):
Review Comment:
Yes, this definitely works.
My point was just that we could structure transforms slightly differently, so that we don't need to bind in most situations. The only time we actually need to get the concrete source type for a transform is when we are calling `apply`. The other method signatures pass a type in. For example, `can_transform(IcebergType)` doesn't need to be specific to a `LongType` -- we can write a version for `BucketTransform` instead of for `BucketNumberTransform`.
In that case, we'd change the code so that instead of calling `apply` on `BucketNumberTransform`, we'd call `BucketTransform.bind` to get `Function[int, int]` that implements the hash and bucketing logic.
That refactor may end up being easier to work with in the end because there would be far fewer places where we'd need to bind the transform to a specific type.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r917904928
##########
python/pyiceberg/transforms.py:
##########
@@ -96,6 +127,38 @@ def dedup_name(self) -> str:
def __str__(self) -> str:
return self.__root__
+ def __eq__(self, other: Any) -> bool:
+ if isinstance(other, Transform):
+ return self.__root__ == other.__root__
+ return False
+
+
+class UnboundTransform(Transform):
Review Comment:
If I understand correctly, this is what we already have for each of the classes of Transforms:
```python
def bucket(source_type: IcebergType, num_buckets: int) -> BaseBucketTransform:
if type(source_type) in {IntegerType, LongType, DateType, TimeType, TimestampType, TimestamptzType}:
return BucketNumberTransform(source_type, num_buckets)
elif isinstance(source_type, DecimalType):
return BucketDecimalTransform(source_type, num_buckets)
elif isinstance(source_type, StringType):
return BucketStringTransform(source_type, num_buckets)
elif isinstance(source_type, BinaryType):
return BucketBytesTransform(source_type, num_buckets)
elif isinstance(source_type, FixedType):
return BucketBytesTransform(source_type, num_buckets)
elif isinstance(source_type, UUIDType):
return BucketUUIDTransform(source_type, num_buckets)
else:
raise ValueError(f"Cannot bucket by type: {source_type}")
```
This is actually called on the `.bind()` method by the transform:
```python
bind_func = functools.partial(bucket, num_buckets=BaseBucketTransform.parse(v))
```
As soon as the source_type is known, we can invoke the method and get the actual implementation.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918098722
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,133 @@
+# 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.
+# pylint: disable=keyword-arg-before-vararg
+from enum import Enum
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ List,
+ Optional,
+ Union,
+)
+
+from pydantic import Field, root_validator
+
+from pyiceberg.schema import Schema
+from pyiceberg.transforms import Transform, UnboundTransform
+from pyiceberg.types import IcebergType
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ """Sort order field
+
+ Args:
+ source_id (int): Source column id from the table’s schema
+ transform (str): Transform that is used to produce values to be sorted on from the source column.
+ This is the same transform as described in partition transforms.
+ direction (SortDirection): Sort direction, that can only be either asc or desc
+ null_order (NullOrder): Null order that describes the order of null values when sorted. Can only be either nulls-first or nulls-last
+ """
+
+ def __init__(
+ self,
+ source_id: Optional[int] = None,
+ transform: Optional[Union[Transform, Callable[[IcebergType], Transform]]] = None,
+ direction: Optional[SortDirection] = None,
+ null_order: Optional[NullOrder] = None,
+ **data: Any,
+ ):
+ if source_id is not None:
+ data["source-id"] = source_id
+ if transform is not None:
+ data["transform"] = transform
+ if direction is not None:
+ data["direction"] = direction
+ if null_order is not None:
+ data["null-order"] = null_order
+ super().__init__(**data)
+
+ @root_validator(pre=True)
+ def set_null_order(cls, values: Dict[str, Any]) -> Dict[str, Any]:
+ values["direction"] = values["direction"] if values.get("direction") else SortDirection.ASC
+ if not values.get("null-order"):
+ values["null-order"] = NullOrder.NULLS_FIRST if values["direction"] == SortDirection.ASC else NullOrder.NULLS_LAST
+ return values
+
+ source_id: int = Field(alias="source-id")
+ transform: Transform = Field()
+ direction: SortDirection = Field()
+ null_order: NullOrder = Field(alias="null-order")
+
+ def bind(self, schema: Schema) -> "SortField":
+ return SortField(
+ source_id=self.source_id,
+ transform=(
+ self.transform.bind(schema.find_type(self.source_id))
+ if isinstance(self.transform, UnboundTransform)
Review Comment:
There's no need to make a new `SortField` if this one is already bound, right? This could be:
```python
if isinstance(self.transform, UnboundTransform):
return SortField(..., transform=self.transform.bind(...))
else:
return 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
[GitHub] [iceberg] Fokko commented on pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#issuecomment-1180901197
@rdblue good call, I've updated it to `transform`, which makes a ton of sense to me in the context
--
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
[GitHub] [iceberg] rdblue commented on pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#issuecomment-1181059185
Thanks @Fokko! Good to have this in. And I'm excited to see how much cleaner things are with the new approach to Transform.
--
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
[GitHub] [iceberg] rdblue merged pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue merged PR #5124:
URL: https://github.com/apache/iceberg/pull/5124
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918350636
##########
python/pyiceberg/transforms.py:
##########
@@ -312,6 +293,28 @@ def source_type(self) -> IcebergType:
def width(self) -> int:
return self._width
+ def hash_function(self, source: IcebergType) -> Callable[[Optional[S]], Optional[S]]:
+ source_type = type(source)
+ if source_type in {IntegerType, LongType}:
+
+ def truncate_func(v):
+ return v - v % self._width
+
+ elif source_type in {StringType, BinaryType}:
+
+ def truncate_func(v):
+ return v[0 : min(self._width, len(v))]
Review Comment:
Nice that this reduces code duplication as well.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918002844
##########
python/pyiceberg/table/metadata.py:
##########
@@ -92,6 +96,14 @@ def construct_refs(cls, data: Dict[str, Any]):
data["refs"] = {MAIN_BRANCH: SnapshotRef(snapshot_id=current_snapshot_id, snapshot_ref_type=SnapshotRefType.BRANCH)}
return data
+ def bind(self):
Review Comment:
Hey @rdblue I agree. Modifying the state might not be the best idea. It will make it simpler for now, but probably complicate things in the long run. I've changed it to bind them when using them and returning a new list of sort-orders.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r917462590
##########
python/pyiceberg/transforms.py:
##########
@@ -96,6 +127,38 @@ def dedup_name(self) -> str:
def __str__(self) -> str:
return self.__root__
+ def __eq__(self, other: Any) -> bool:
+ if isinstance(other, Transform):
+ return self.__root__ == other.__root__
+ return False
+
+
+class UnboundTransform(Transform):
Review Comment:
Looking at the Java side a little more, I think there's an alternative to making this `UnboundTransform` change. The Java implementation really only needs the source type for the `apply` method. I think you could solve this problem by changing the `Transform` API. Instead of having `apply` on `Transform`, you could put `apply` on a `Transformer` class, then add `forType(t: IcebergType) -> Transformer` to `Transform`. That may be cleaner in the long term, although I think this works for now.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r907956475
##########
python/src/iceberg/table/sorting.py:
##########
@@ -0,0 +1,60 @@
+# 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.
+from dataclasses import dataclass
+from enum import Enum
+from typing import List, Optional
+
+from iceberg.transforms import Transform
+
+
+class SortDirection(Enum):
+ asc = "asc"
+ desc = "desc"
+
+
+class NullOrder(Enum):
+ nulls_first = "nulls-first"
+ nulls_last = "nulls-last"
+
+
+@dataclass(frozen=True)
+class SortField:
+ source_id: int
+ transform: Transform
+ direction: SortDirection
+ null_order: NullOrder
+
+
+@dataclass(frozen=True)
Review Comment:
Should these be Pydantic classes?
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918229694
##########
python/pyiceberg/transforms.py:
##########
@@ -96,6 +127,38 @@ def dedup_name(self) -> str:
def __str__(self) -> str:
return self.__root__
+ def __eq__(self, other: Any) -> bool:
+ if isinstance(other, Transform):
+ return self.__root__ == other.__root__
+ return False
+
+
+class UnboundTransform(Transform):
Review Comment:
It may not be something that we want to do in this PR. We can follow up to change it, probably
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r917459858
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,133 @@
+# 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.
+# pylint: disable=keyword-arg-before-vararg
+
+from enum import Enum
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ List,
+ Optional,
+ Union,
+)
+
+from pydantic import Field, root_validator
+
+from pyiceberg.schema import Schema
+from pyiceberg.transforms import Transform, UnboundTransform
+from pyiceberg.types import IcebergType
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ """A field that provides information on how the table is sorted
Review Comment:
This doesn't necessarily have information on how the table is sorted. These are defined sort orders. There's not necessarily any data in the sort order in a given table.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r917462963
##########
python/pyiceberg/table/metadata.py:
##########
@@ -92,6 +96,14 @@ def construct_refs(cls, data: Dict[str, Any]):
data["refs"] = {MAIN_BRANCH: SnapshotRef(snapshot_id=current_snapshot_id, snapshot_ref_type=SnapshotRefType.BRANCH)}
return data
+ def bind(self):
Review Comment:
The main issue I have with this commit is that binding is done to transform existing state. I think that's going to cause problems later.
For example, if I load a table and bind all of the sort orders to the schema, what happens when I then update the schema? I think we would normally want to be able to copy all of the sort orders into a new `TableMetadata` object, but we would actually have to "unbind" them and rebind them to the new schema. This in-place binding is hard to work with.
Instead, I'd recommend having separate lists of unbound and bound things. Then when you want to get a sort order for a particular write, you can get the unbound order, bind it to the write schema, and know it is going to work.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r917897236
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,133 @@
+# 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.
+# pylint: disable=keyword-arg-before-vararg
+
+from enum import Enum
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ List,
+ Optional,
+ Union,
+)
+
+from pydantic import Field, root_validator
+
+from pyiceberg.schema import Schema
+from pyiceberg.transforms import Transform, UnboundTransform
+from pyiceberg.types import IcebergType
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ """A field that provides information on how the table is sorted
+
+ Args:
+ source_id (int): Source column id from the table’s schema
+ transform (str): Transform that is used to produce values to be sorted on from the source column.
+ This is the same transform as described in partition transforms.
+ source_id (SortDirection): Sort direction, that can only be either asc or desc
+ source_id (NullOrder): Null order that describes the order of null values when sorted. Can only be either nulls-first or nulls-last
+ """
+
+ class Config:
+ frozen = False
+
+ def __init__(
+ self,
+ source_id: Optional[int] = None,
+ transform: Optional[Union[Transform, Callable[[IcebergType], Transform]]] = None,
+ direction: Optional[SortDirection] = None,
+ null_order: Optional[NullOrder] = None,
+ **data: Any,
+ ):
+ if source_id is not None:
+ data["source-id"] = source_id
+ if transform is not None:
+ data["transform"] = transform
+ if direction is not None:
+ data["direction"] = direction
+ if null_order is not None:
+ data["null-order"] = null_order
+ super().__init__(**data)
+
+ @root_validator(pre=True)
+ def set_null_order(cls, values: Dict[str, Any]) -> Dict[str, Any]:
+ values["direction"] = values["direction"] if values.get("direction") else SortDirection.ASC
Review Comment:
Of course, you can put everything in there. This will be checked when the validator does its job, but that hasn't been done at the `pre_validator` step.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918345040
##########
python/pyiceberg/transforms.py:
##########
@@ -96,25 +125,27 @@ def dedup_name(self) -> str:
def __str__(self) -> str:
return self.__root__
+ def __eq__(self, other: Any) -> bool:
+ if isinstance(other, Transform):
+ return self.__root__ == other.__root__
+ return False
-class BaseBucketTransform(Transform[S, int]):
+
+class BucketTransform(Transform[S, int]):
"""Base Transform class to transform 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, FixedType, UUIDType.
num_buckets (int): The number of buckets.
"""
_source_type: IcebergType = PrivateAttr()
_num_buckets: PositiveInt = PrivateAttr()
- def __init__(self, source_type: IcebergType, num_buckets: int, **data: Any):
+ def __init__(self, num_buckets: int, **data: Any):
super().__init__(__root__=f"bucket[{num_buckets}]", **data)
- self._source_type = source_type
Review Comment:
Remove the `_source_type` field as well?
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918341688
##########
python/pyiceberg/transforms.py:
##########
@@ -96,6 +127,38 @@ def dedup_name(self) -> str:
def __str__(self) -> str:
return self.__root__
+ def __eq__(self, other: Any) -> bool:
+ if isinstance(other, Transform):
+ return self.__root__ == other.__root__
+ return False
+
+
+class UnboundTransform(Transform):
Review Comment:
Sounds great!
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912542665
##########
python/tests/table/test_sorting.py:
##########
@@ -0,0 +1,53 @@
+# 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.
+from pyiceberg import transforms
+from pyiceberg.table.sorting import (
+ NullOrder,
+ SortDirection,
+ SortField,
+ SortOrder,
+)
+from pyiceberg.transforms import IdentityTransform
+from pyiceberg.types import IntegerType, StringType
+
+
+def test_serialize_sort_order():
Review Comment:
Just updated this with a `UnboundTransform` that deserializes properly back and forth, and can be bound using the `bind()` method. Also added a lot of tests 👍🏻
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r911737328
##########
python/src/iceberg/table/sorting.py:
##########
@@ -0,0 +1,60 @@
+# 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.
+from dataclasses import dataclass
+from enum import Enum
+from typing import List, Optional
+
+from iceberg.transforms import Transform
+
+
+class SortDirection(Enum):
+ asc = "asc"
+ desc = "desc"
+
+
+class NullOrder(Enum):
+ nulls_first = "nulls-first"
+ nulls_last = "nulls-last"
+
+
+@dataclass(frozen=True)
+class SortField:
+ source_id: int
+ transform: Transform
+ direction: SortDirection
+ null_order: NullOrder
+
+
+@dataclass(frozen=True)
Review Comment:
Now the PR has been merged, I'll update it to Pydantic right away
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918096821
##########
python/pyiceberg/table/metadata.py:
##########
@@ -159,10 +163,14 @@ def construct_refs(cls, data: Dict[str, Any]):
remove oldest metadata log entries and keep a fixed-size log of the most
recent entries after a commit."""
- sort_orders: List[Dict[str, Any]] = Field(alias="sort-orders", default_factory=list)
+ sort_orders: List[SortOrder] = Field(alias="sort-orders", default_factory=list)
"""A list of sort orders, stored as full sort order objects."""
- default_sort_order_id: int = Field(alias="default-sort-order-id", default=DEFAULT_SORT_ORDER_UNSORTED)
+ @property
+ def bound_sort_orders(self) -> List[SortOrder]:
+ return [sort_order.bind(self.current_schema()) for sort_order in self.sort_orders]
Review Comment:
For now, I'd probably just make one accessor that binds the default sort order to the current schema. I'm not sure if it will be valuable to have all of the known sort orders bound to a particular schema.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918348241
##########
python/pyiceberg/transforms.py:
##########
@@ -130,99 +161,58 @@ def apply(self, value: Optional[S]) -> Optional[int]:
def result_type(self, source: IcebergType) -> IcebergType:
return IntegerType()
- @abstractmethod
- def can_transform(self, source: IcebergType) -> bool:
- pass
-
- def __repr__(self) -> str:
- return f"transforms.bucket(source_type={repr(self._source_type)}, num_buckets={self._num_buckets})"
-
-
-class BucketNumberTransform(BaseBucketTransform):
- """Transforms a value of IntegerType, LongType, DateType, TimeType, TimestampType, or TimestamptzType
- into a bucket partition value
-
- Example:
- >>> transform = BucketNumberTransform(LongType(), 100)
- >>> transform.apply(81068000000)
- 59
- """
-
def can_transform(self, source: IcebergType) -> bool:
- return type(source) in {IntegerType, DateType, LongType, TimeType, TimestampType, TimestamptzType}
-
- def hash(self, value) -> int:
- return mmh3.hash(struct.pack("<q", value))
-
-
-class BucketDecimalTransform(BaseBucketTransform):
- """Transforms a value of DecimalType into a bucket partition value.
-
- Example:
- >>> transform = BucketDecimalTransform(DecimalType(9, 2), 100)
- >>> transform.apply(Decimal("14.20"))
- 59
- """
-
- def can_transform(self, source: IcebergType) -> bool:
- return isinstance(source, DecimalType)
-
- def hash(self, value: Decimal) -> int:
- return mmh3.hash(decimal_to_bytes(value))
-
-
-class BucketStringTransform(BaseBucketTransform):
- """Transforms a value of StringType into a bucket partition value.
-
- Example:
- >>> transform = BucketStringTransform(StringType(), 100)
- >>> transform.apply("iceberg")
- 89
- """
-
- def can_transform(self, source: IcebergType) -> bool:
- return isinstance(source, StringType)
-
- def hash(self, value: str) -> int:
- return mmh3.hash(value)
-
-
-class BucketBytesTransform(BaseBucketTransform):
- """Transforms a value of FixedType or BinaryType into a bucket partition value.
-
- Example:
- >>> transform = BucketBytesTransform(BinaryType(), 100)
- >>> transform.apply(b"\\x00\\x01\\x02\\x03")
- 41
- """
-
- def can_transform(self, source: IcebergType) -> bool:
- return type(source) in {FixedType, BinaryType}
-
- def hash(self, value: bytes) -> int:
- return mmh3.hash(value)
+ return type(source) in {
+ IntegerType,
+ DateType,
+ LongType,
+ TimeType,
+ TimestampType,
+ TimestamptzType,
+ DecimalType,
+ StringType,
+ FixedType,
+ BinaryType,
+ UUIDType,
+ }
+
+ def hash_function(self, source: IcebergType, bucket: bool = True) -> Callable[[Optional[Any]], Optional[int]]:
+ source_type = type(source)
+ if source_type in {IntegerType, LongType, DateType, TimeType, TimestampType, TimestamptzType}:
+
+ def hash_func(v):
+ return mmh3.hash(struct.pack("<q", v))
+
+ elif source_type == DecimalType:
+
+ def hash_func(v):
+ return mmh3.hash(decimal_to_bytes(v))
+
+ elif source_type in {StringType, FixedType, BinaryType}:
+
+ def hash_func(v):
+ return mmh3.hash(v)
+
+ elif source_type == UUIDType:
+
+ def hash_func(v):
Review Comment:
Is there a performance penalty for defining functions like this? We could also make these top-level, like `def _hash_uuid(uuid: UUID) -> int: ...` and return references here.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918351433
##########
python/pyiceberg/transforms.py:
##########
@@ -418,69 +392,39 @@ class UnknownTransform(Transform):
_source_type: IcebergType = PrivateAttr()
_transform: str = PrivateAttr()
- def __init__(self, source_type: IcebergType, transform: str, **data: Any):
+ def __init__(self, transform: str, **data: Any):
super().__init__(**data)
- self._source_type = source_type
self._transform = transform
- def apply(self, value: Optional[S]):
+ def hash_function(self, source: IcebergType) -> Callable[[Optional[S]], Optional[T]]:
raise AttributeError(f"Cannot apply unsupported transform: {self}")
def can_transform(self, source: IcebergType) -> bool:
- return self._source_type == source
+ return False
Review Comment:
We may need to change this later. I'm not sure what the implication will be.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918359810
##########
python/pyiceberg/transforms.py:
##########
@@ -64,11 +72,32 @@ class Transform(IcebergBaseModel, ABC, Generic[S, T]):
__root__: str = Field()
- def __call__(self, value: Optional[S]) -> Optional[T]:
- return self.apply(value)
+ @classmethod
+ def __get_validators__(cls):
+ # one or more validators may be yielded which will be called in the
+ # order to validate the input, each validator will receive as an input
+ # the value returned from the previous validator
+ yield cls.validate
+
+ @classmethod
+ def validate(cls, v: Any):
+ # When Pydantic is unable to determine the subtype
+ # In this case we'll help pydantic a bit by parsing the transform type ourselves
+ if isinstance(v, str):
+ if v == IDENTITY:
+ return IdentityTransform()
+ elif v == VOID:
+ return VoidTransform()
+ elif v.startswith(BUCKET):
+ return BucketTransform(num_buckets=BUCKET_PARSER.match(v))
+ elif v.startswith(TRUNCATE):
+ return TruncateTransform(width=BUCKET_PARSER.match(v))
+ else:
+ return UnknownTransform(transform=v)
+ return v
@abstractmethod
- def apply(self, value: Optional[S]) -> Optional[T]:
+ def hash_function(self, source: IcebergType) -> Callable[[Optional[S]], Optional[T]]:
Review Comment:
Good call, I've updated the code
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918362427
##########
python/pyiceberg/transforms.py:
##########
@@ -418,69 +392,39 @@ class UnknownTransform(Transform):
_source_type: IcebergType = PrivateAttr()
_transform: str = PrivateAttr()
- def __init__(self, source_type: IcebergType, transform: str, **data: Any):
+ def __init__(self, transform: str, **data: Any):
super().__init__(**data)
- self._source_type = source_type
self._transform = transform
- def apply(self, value: Optional[S]):
+ def hash_function(self, source: IcebergType) -> Callable[[Optional[S]], Optional[T]]:
raise AttributeError(f"Cannot apply unsupported transform: {self}")
def can_transform(self, source: IcebergType) -> bool:
- return self._source_type == source
+ return False
Review Comment:
I had the same feeling, but the `UnknownTransform` feels like a transform that you don't want to use anyway. Returning `False`, felt like the right thing to do.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r917459515
##########
python/pyiceberg/table/metadata.py:
##########
@@ -62,21 +62,25 @@ def check_partition_specs(values: Dict[str, Any]) -> Dict[str, Any]:
def check_sort_orders(values: Dict[str, Any]) -> Dict[str, Any]:
"""Validator to check if the default_sort_order_id is present in sort-orders"""
- default_sort_order_id = values["default_sort_order_id"]
+ default_sort_order_id: int = values["default_sort_order_id"]
- if default_sort_order_id != DEFAULT_SORT_ORDER_UNSORTED:
- for sort in values["sort_orders"]:
- if sort["order-id"] == default_sort_order_id:
+ if default_sort_order_id != UNSORTED_SORT_ORDER_ID:
+ sort_orders: List[SortOrder] = values["sort_orders"]
+ for sort_order in sort_orders:
+ if sort_order.order_id == default_sort_order_id:
return values
- raise ValidationError(f"default-sort-order-id {default_sort_order_id} can't be found")
+ raise ValidationError(f"default-sort-order-id {default_sort_order_id} can't be found in {sort_orders}")
return values
class TableMetadataCommonFields(IcebergBaseModel):
"""Metadata for an Iceberg table as specified in the Apache Iceberg
spec (https://iceberg.apache.org/spec/#iceberg-table-spec)"""
+ def current_schema(self) -> Schema:
+ return next(schema for schema in self.schemas if schema.schema_id == self.current_schema_id)
Review Comment:
We may want to index these for quick lookup, but it seems minor. I'm not really sure if it is worth it.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r917893173
##########
python/pyiceberg/table/metadata.py:
##########
@@ -62,21 +62,25 @@ def check_partition_specs(values: Dict[str, Any]) -> Dict[str, Any]:
def check_sort_orders(values: Dict[str, Any]) -> Dict[str, Any]:
"""Validator to check if the default_sort_order_id is present in sort-orders"""
- default_sort_order_id = values["default_sort_order_id"]
+ default_sort_order_id: int = values["default_sort_order_id"]
- if default_sort_order_id != DEFAULT_SORT_ORDER_UNSORTED:
- for sort in values["sort_orders"]:
- if sort["order-id"] == default_sort_order_id:
+ if default_sort_order_id != UNSORTED_SORT_ORDER_ID:
+ sort_orders: List[SortOrder] = values["sort_orders"]
+ for sort_order in sort_orders:
+ if sort_order.order_id == default_sort_order_id:
return values
- raise ValidationError(f"default-sort-order-id {default_sort_order_id} can't be found")
+ raise ValidationError(f"default-sort-order-id {default_sort_order_id} can't be found in {sort_orders}")
return values
class TableMetadataCommonFields(IcebergBaseModel):
"""Metadata for an Iceberg table as specified in the Apache Iceberg
spec (https://iceberg.apache.org/spec/#iceberg-table-spec)"""
+ def current_schema(self) -> Schema:
+ return next(schema for schema in self.schemas if schema.schema_id == self.current_schema_id)
Review Comment:
This will stop the iteration when it finds it. We could also cache it. When we have more lookups on a specific id I think it makes sense to index it.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918202107
##########
python/pyiceberg/transforms.py:
##########
@@ -96,6 +127,38 @@ def dedup_name(self) -> str:
def __str__(self) -> str:
return self.__root__
+ def __eq__(self, other: Any) -> bool:
+ if isinstance(other, Transform):
+ return self.__root__ == other.__root__
+ return False
+
+
+class UnboundTransform(Transform):
Review Comment:
Ah, I see where you're going. Thanks for the explanaition. I like it, but it involves a bit more code changes. Let me give it a swing.
##########
python/pyiceberg/transforms.py:
##########
@@ -96,6 +127,38 @@ def dedup_name(self) -> str:
def __str__(self) -> str:
return self.__root__
+ def __eq__(self, other: Any) -> bool:
+ if isinstance(other, Transform):
+ return self.__root__ == other.__root__
+ return False
+
+
+class UnboundTransform(Transform):
Review Comment:
Ah, I see where you're going. Thanks for the explanation. I like it, but it involves a bit more code changes. Let me give it a swing.
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912062557
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,84 @@
+# 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.
+from enum import Enum
+from typing import Any, List, Optional
+
+from pydantic import Field
+
+from pyiceberg.transforms import Transform
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(str, Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(str, Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ def __init__(
+ self,
+ source_id: int,
+ transform: Transform,
+ direction: SortDirection = SortDirection.ASC,
+ null_order: NullOrder = NullOrder.NULLS_LAST,
+ **data: Any,
+ ):
+ data["source-id"] = source_id
+ data["transform"] = transform
+ data["direction"] = direction
+ data["null-order"] = null_order
+ super().__init__(**data)
+
+ source_id: int = Field(alias="source-id")
+ transform: Transform = Field()
+ direction: SortDirection = Field()
+ null_order: NullOrder = Field(alias="null-order")
+
+
+class SortOrder(IcebergBaseModel):
+ """
+ Users can sort their data within partitions by columns to gain performance.
+ The information on how the data is sorted can be declared per data or delete file, by a sort order.
+
+ The order of the sort fields within the list defines the order in which the sort is applied to the data.
+
+ Each sort field consists of:
+
+ - Source column id from the table’s schema
+ - Transform that is used to produce values to be sorted on from the source column.
+ This is the same transform as described in partition transforms.
+ - Sort direction, that can only be either asc or desc
+ - Null order that describes the order of null values when sorted. Can only be either nulls-first or nulls-last
+ """
+
+ def __init__(self, order_id: int, *fields: SortField, **data: Any):
+ data["order-id"] = order_id
+ if fields:
+ data["fields"] = fields
+ super().__init__(**data)
+
+ order_id: Optional[int] = Field(alias="order-id")
+ fields: List[SortField] = Field(default_factory=list)
+
+
+UNPARTITIONED_SORT_ORDER_ID = 0
Review Comment:
I think you mean `UNSORTED` rather than `UNPARTITIONED`?
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912498839
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,84 @@
+# 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.
+from enum import Enum
+from typing import Any, List, Optional
+
+from pydantic import Field
+
+from pyiceberg.transforms import Transform
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(str, Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(str, Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ def __init__(
+ self,
+ source_id: int,
+ transform: Transform,
+ direction: SortDirection = SortDirection.ASC,
+ null_order: NullOrder = NullOrder.NULLS_LAST,
+ **data: Any,
+ ):
+ data["source-id"] = source_id
+ data["transform"] = transform
+ data["direction"] = direction
+ data["null-order"] = null_order
+ super().__init__(**data)
+
+ source_id: int = Field(alias="source-id")
+ transform: Transform = Field()
+ direction: SortDirection = Field()
+ null_order: NullOrder = Field(alias="null-order")
+
+
+class SortOrder(IcebergBaseModel):
+ """
+ Users can sort their data within partitions by columns to gain performance.
+ The information on how the data is sorted can be declared per data or delete file, by a sort order.
+
+ The order of the sort fields within the list defines the order in which the sort is applied to the data.
+
+ Each sort field consists of:
+
+ - Source column id from the table’s schema
+ - Transform that is used to produce values to be sorted on from the source column.
+ This is the same transform as described in partition transforms.
+ - Sort direction, that can only be either asc or desc
+ - Null order that describes the order of null values when sorted. Can only be either nulls-first or nulls-last
+ """
+
+ def __init__(self, order_id: int, *fields: SortField, **data: Any):
+ data["order-id"] = order_id
+ if fields:
+ data["fields"] = fields
+ super().__init__(**data)
+
+ order_id: Optional[int] = Field(alias="order-id")
+ fields: List[SortField] = Field(default_factory=list)
+
+
+UNPARTITIONED_SORT_ORDER_ID = 0
Review Comment:
Working at two things at the same time lol, thanks!
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912526743
##########
python/tests/table/test_sorting.py:
##########
@@ -0,0 +1,53 @@
+# 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.
+from pyiceberg import transforms
+from pyiceberg.table.sorting import (
+ NullOrder,
+ SortDirection,
+ SortField,
+ SortOrder,
+)
+from pyiceberg.transforms import IdentityTransform
+from pyiceberg.types import IntegerType, StringType
+
+
+def test_serialize_sort_order():
Review Comment:
I was working on something similar, thanks!
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r907956353
##########
python/src/iceberg/table/sorting.py:
##########
@@ -0,0 +1,60 @@
+# 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.
+from dataclasses import dataclass
+from enum import Enum
+from typing import List, Optional
+
+from iceberg.transforms import Transform
+
+
+class SortDirection(Enum):
+ asc = "asc"
+ desc = "desc"
Review Comment:
ALL CAPS?
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918318438
##########
python/pyiceberg/table/metadata.py:
##########
@@ -159,10 +163,14 @@ def construct_refs(cls, data: Dict[str, Any]):
remove oldest metadata log entries and keep a fixed-size log of the most
recent entries after a commit."""
- sort_orders: List[Dict[str, Any]] = Field(alias="sort-orders", default_factory=list)
+ sort_orders: List[SortOrder] = Field(alias="sort-orders", default_factory=list)
"""A list of sort orders, stored as full sort order objects."""
- default_sort_order_id: int = Field(alias="default-sort-order-id", default=DEFAULT_SORT_ORDER_UNSORTED)
+ @property
+ def bound_sort_orders(self) -> List[SortOrder]:
+ return [sort_order.bind(self.current_schema()) for sort_order in self.sort_orders]
Review Comment:
With the new changes, we can revert all of this. I agree that it is kinda awkward. Let me know what you think.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918317889
##########
python/pyiceberg/transforms.py:
##########
@@ -96,6 +127,38 @@ def dedup_name(self) -> str:
def __str__(self) -> str:
return self.__root__
+ def __eq__(self, other: Any) -> bool:
+ if isinstance(other, Transform):
+ return self.__root__ == other.__root__
+ return False
+
+
+class UnboundTransform(Transform):
Review Comment:
I have a working version, which make the code much simpler, which I like. I think it makes sense to do it in this PR, since it will remove 80% of the tests I already wrote :) I think the code is much nicer because we can omit the bind() stuff, including all the copying of the object.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r918358878
##########
python/pyiceberg/transforms.py:
##########
@@ -96,25 +125,27 @@ def dedup_name(self) -> str:
def __str__(self) -> str:
return self.__root__
+ def __eq__(self, other: Any) -> bool:
+ if isinstance(other, Transform):
+ return self.__root__ == other.__root__
+ return False
-class BaseBucketTransform(Transform[S, int]):
+
+class BucketTransform(Transform[S, int]):
"""Base Transform class to transform 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, FixedType, UUIDType.
num_buckets (int): The number of buckets.
"""
_source_type: IcebergType = PrivateAttr()
_num_buckets: PositiveInt = PrivateAttr()
- def __init__(self, source_type: IcebergType, num_buckets: int, **data: Any):
+ def __init__(self, num_buckets: int, **data: Any):
super().__init__(__root__=f"bucket[{num_buckets}]", **data)
- self._source_type = source_type
Review Comment:
We don't know the `_source_type` when initializing the transform, this allows us to omit the `UnboundTransform`
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r917895231
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,133 @@
+# 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.
+# pylint: disable=keyword-arg-before-vararg
+
+from enum import Enum
+from typing import (
+ Any,
+ Callable,
+ Dict,
+ List,
+ Optional,
+ Union,
+)
+
+from pydantic import Field, root_validator
+
+from pyiceberg.schema import Schema
+from pyiceberg.transforms import Transform, UnboundTransform
+from pyiceberg.types import IcebergType
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ """A field that provides information on how the table is sorted
+
+ Args:
+ source_id (int): Source column id from the table’s schema
+ transform (str): Transform that is used to produce values to be sorted on from the source column.
+ This is the same transform as described in partition transforms.
+ source_id (SortDirection): Sort direction, that can only be either asc or desc
Review Comment:
Copy/paste, thanks! I need to set a checker on this some day
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r911737004
##########
python/src/iceberg/table/sorting.py:
##########
@@ -0,0 +1,60 @@
+# 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.
+from dataclasses import dataclass
+from enum import Enum
+from typing import List, Optional
+
+from iceberg.transforms import Transform
+
+
+class SortDirection(Enum):
+ asc = "asc"
+ desc = "desc"
Review Comment:
THIS WAS BY THE OPEN-API GENERATOR THAT I USED. BUT I PREFER CAPS AS WELL.
--
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
[GitHub] [iceberg] kbendick commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
kbendick commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912174719
##########
python/pyiceberg/table/metadata.py:
##########
@@ -270,7 +271,7 @@ def set_sort_orders(cls, data: Dict[str, Any]):
# This is going to be much nicer as soon as sort-order is an actual pydantic object
# Probably we'll just create a UNSORTED_ORDER constant then
Review Comment:
Do these two lines still apply now that we have the constants and are using `IcebergBaseModel`?
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912514043
##########
python/tests/table/test_sorting.py:
##########
@@ -0,0 +1,53 @@
+# 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.
+from pyiceberg import transforms
+from pyiceberg.table.sorting import (
+ NullOrder,
+ SortDirection,
+ SortField,
+ SortOrder,
+)
+from pyiceberg.transforms import IdentityTransform
+from pyiceberg.types import IntegerType, StringType
+
+
+def test_serialize_sort_order():
Review Comment:
In Java, we recently introduced `UnboundSortOrder` and `UnboundPartitionSpec` to fix this problem. We may want to do the same here, where the transform is not instantiated until the order is bound to a schema.
--
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
[GitHub] [iceberg] Fokko commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
Fokko commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912498255
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,84 @@
+# 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.
+from enum import Enum
+from typing import Any, List, Optional
+
+from pydantic import Field
+
+from pyiceberg.transforms import Transform
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(str, Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(str, Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ def __init__(
+ self,
+ source_id: int,
+ transform: Transform,
+ direction: SortDirection = SortDirection.ASC,
+ null_order: NullOrder = NullOrder.NULLS_LAST,
Review Comment:
That makes a lot of sense, thanks!
--
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
[GitHub] [iceberg] rdblue commented on a diff in pull request #5124: Python: Add sort order fields
Posted by GitBox <gi...@apache.org>.
rdblue commented on code in PR #5124:
URL: https://github.com/apache/iceberg/pull/5124#discussion_r912060237
##########
python/pyiceberg/table/sorting.py:
##########
@@ -0,0 +1,84 @@
+# 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.
+from enum import Enum
+from typing import Any, List, Optional
+
+from pydantic import Field
+
+from pyiceberg.transforms import Transform
+from pyiceberg.utils.iceberg_base_model import IcebergBaseModel
+
+
+class SortDirection(str, Enum):
+ ASC = "asc"
+ DESC = "desc"
+
+
+class NullOrder(str, Enum):
+ NULLS_FIRST = "nulls-first"
+ NULLS_LAST = "nulls-last"
+
+
+class SortField(IcebergBaseModel):
+ def __init__(
+ self,
+ source_id: int,
+ transform: Transform,
+ direction: SortDirection = SortDirection.ASC,
+ null_order: NullOrder = NullOrder.NULLS_LAST,
Review Comment:
The null order should be defaulted to [correspond to the sort direction](https://github.com/apache/iceberg/blob/master/spark/v3.3/spark-extensions/src/main/scala/org/apache/spark/sql/catalyst/parser/extensions/IcebergSqlExtensionsAstBuilder.scala#L180). If the direction is ASC, then the null order should be NULLS FIRST. If the direction is DESC, then then null order should be NULLS LAST.
--
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