Repository navigation
[WIP] Extend metadata with SortOrder - #589
aokolnychyi wants to merge 1 commit into
Conversation
| import java.util.Objects; | ||
| import org.apache.iceberg.SortTransforms.SortTransform; | ||
|
|
||
| public class SortField implements Serializable { |
There was a problem hiding this comment.
Alternatively, we can try to have a hierarchy of classes here (e.g. SortField, SingleColumnSortField, etc) with different JSON representations. This will complicate the parsing logic, though.
| private final SortTransform transform; | ||
| private final int[] sourceIds; | ||
|
|
||
| SortField(String name, Direction direction, NullOrder nullOrder, SortTransform transform, int[] sourceIds) { |
| return sourceIds; | ||
| } | ||
|
|
||
| public boolean semanticEquals(SortField that) { |
| // TODO: toString() | ||
| public class SortOrder implements Serializable { | ||
|
|
||
| private static final SortOrder UNSORTED_ORDER = new SortOrder(new Schema(), 0, ImmutableList.of()); |
There was a problem hiding this comment.
Does this mean that order ID 0 is reserved for the unsorted order?
There was a problem hiding this comment.
Nit: Collections.emptyList() also returns an immutable list
| this.schema = schema; | ||
| this.orderId = orderId; | ||
| this.fields = new SortField[fields.size()]; | ||
| for (int fieldIndex = 0; fieldIndex < this.fields.length; fieldIndex++) { |
There was a problem hiding this comment.
Nit: could use fields.toArray(new SortField[fields.length]) instead.
| private final String name; | ||
| private final Direction direction; | ||
| private final NullOrder nullOrder; | ||
| private final SortTransform transform; |
There was a problem hiding this comment.
I think it is likely that sort transforms and partition transforms mostly overlap, so we may consider using the same Transform class for both.
When configuring a table's sort order, I think we want to allow both an order across tasks as well as a local order in a single task. Then, the table can be configured with an ordering that includes partition columns so that Iceberg can tell the processing engine to use an ordering for a write that includes partitions.
A concrete use case is that we have a table partitioned by date(ts) and bucket(id, 16), and we want Spark to write using date(ts), bucket(id, 16), and finally, id. If we want partitions in the sort order, then we will need to support all of those transforms and probably want to standardize on Transform.
There was a problem hiding this comment.
I agree that sharing transforms between SortOrder and PartitionSpec is a good idea (if we want to include date(ts), bucket(id, 16) in the sort definition).
W.r.t the order within/across tasks. Did I get correctly the idea is that query engines should sort data globally/locally depending on whether partition columns are included in the sort order? If yes, I have a couple of questions. For example, we can have multiple pipelines writing to the same table. While it is beneficial to sort data globally in batch jobs, we might want to sort data within tasks or disable sorting at all in streaming jobs. Internally, we allow our customers to configure their sort mode on write via a SQL config. That gives them the needed flexibility to configure the sort mode per job. Since we plan to annotate files with sort_order_id, compaction jobs might take that into account as well. Is it reasonable to say the sort mode (global, local, none) should be configurable per job rather than per table?
My original understanding was that SortOrder should apply only within partitions. Basically, the actual sort key is derived by combining partition and sort values (which should be done by query engines). Also, not including partition columns in the sort key won’t work because we will generate a lot of files per task. Basically, the original idea was not to include partition columns in SortOrder but include them in the actual sort key. Is this reasonable? In which case we won't want partition values to be part of our sort key?
There was a problem hiding this comment.
Iceberg should support configuring an order that gets applied to all jobs writing to a table. We want to enable building services that can make changes to a table, like the file format, compression, or sort order used. Embedding the sort order in a job requires having a human change the job and not just table configuration because it requires editing SQL or rewriting a DataFrame operation. Sort order should be declarative, not imperative.
You're right that there are times want to have control over a write in a job. For example, you may want to write unsorted data to meet an SLA, but then have a service go rewrite that data with a more optimal sort order. I think this need is less common and the default should be to use the sort order from the table's configuration. We just need a way to override the table configuration.
Also, table configuration should support both local and global ordering. Our best practice is to use a global ordering to handle skew, prepare data for filters, and make the data encode or compress better. But, maybe this should be configured separately, like Hive's DISTRIBUTE BY and SORT BY. What do you think?
There was a problem hiding this comment.
I think DISTRIBUTE BY and SORT BY can be potentially quite flexible. As those clauses have specific meanings in Hive/Spark, we probably need to support ORDER BY and CLUSTER BY (optionally) in order to express arbitrary sort orders. For example, we cannot express a global sort order with DISTRIBUTE BY and SORT BY.
We can have something like below:
Case 1
Iceberg:
SortOrder.builderFor(schema)
.distributeBy("part_col")
.distributeBy(bucket("ts", 16))
.sortBy("id")
.build()
Query engines:
Sort("id", global = false)
HashPartitioning(bucket("ts", 16), "part_col")
Case 2
Iceberg:
SortOrder.builderFor(schema)
.orderBy("part_col_1")
.orderBy("part_col_2")
.orderBy("id")
.build()
Query engines:
Sort("part_col_1", "part_col_2", "id", global = true)
Case 3
Iceberg:
SortOrder.builderFor(schema)
.clusterBy("part_col_1")
.clusterBy("part_col_2")
.sortBy("id")
.build()
Query engines:
Sort("part_col_1", "part_col_2", "id", global = false)
HashPartitioning("part_col_1", "part_col_2")
There was a problem hiding this comment.
In Spark, we will need a way how to define a sort order in DDLs as well as to extend DS V2 so that tables can report their ordering. @rdblue, what do you think?
There was a problem hiding this comment.
Yes, I intentionally used the definition of DISTRIBUTE BY, SORT BY, CLUSTER BY that both Spark and Hive support in queries and not CLUSTERED BY currently present in create table statements. I find it a bit odd that CLUSTER BY and CLUSTERED BY mean different things. At the same time, materialized views in Hive do support that syntax.
I went through the discussion on the dev list and have a question. How can I represent a local sort within tasks with the proposed API (i.e. without any shuffles)? I believe it is a common use case and even Iceberg requires that entries for the same partition are next to each other within the same task.
One of my early ideas was to support the following DDLs:
...
PARTITIONED BY
DISTRIBUTED BY
SORTED BY
...
...
PARTITIONED BY
DISTRIBUTED BY
...
...
PARTITIONED BY
SORTED BY
...
...
PARTITIONED BY
ORDERED BY
...
We can use transforms to add bucketing and we can also support the old CLUSTERED BY alone without new clauses for compatibility. Meaning of SORTED BY will stay close to the current one. On top, we add DISTRIBUTED BY and ORDERED BY with their current meaning in Spark.
Then we can map those DDLs into the following write distributions:
LocalDistribution
- sortBy: Seq[Expression]
RangeBasedDistribution
- distributeBy: Seq[Expression]
- sortBy: Seq[Expression]
HashBasedDistribution
- distributeBy: Seq[Expression]
- sortBy: Seq[Expression]
Then RangeBasedDistribution can be represented as a global sort depending on distributeBy and sortBy.
I haven't thought a lot about this, will check the dev discussion again tomorrow.
There was a problem hiding this comment.
I took a look at the Spark dev discussion one more time and it still looks there is no way to express a local sort without shuffles. After a closer look at Hive, seems they only allow DISTRIBUTED BY and SORTED BY together while creating materialized views. In queries, those two can be used independently. I wonder if it is only me who thinks it is relevant to support a local sort. @rdblue, what do you think?
There was a problem hiding this comment.
There are also certain cases when we write to a table but we don't control the behavior. For example, during eager UPDATEs/DELETEs/MERGEs. Asking for a global sort while writing updated records back might be expensive (apart from the shuffle itself, skew estimation might recompute some parts twice). In those cases, it is cheaper to optimize the updated partitions later on.
There was a problem hiding this comment.
I think MERGE should be handled separately because that will depend on other configuration. You're right that it will also require distribution that is unlikely to match the table's ideal distribution.
There was a problem hiding this comment.
I don't like using both SORT BY and ORDER BY. Because there is no obvious difference between them, I think it is confusing. I'd rather use ORDER BY for global ordering and maybe add a LOCAL keyword to change that: LOCAL ORDER BY col1, col2.
If we did that, then we could use LOCAL ORDER BY with DISTRIBUTE BY or ORDER BY on its own. We could also infer that ORDER BY is local if DISTRIBUTE BY is present. What do you think?
| this.schema = schema; | ||
| } | ||
|
|
||
| public Builder natural(String columnName) { |
There was a problem hiding this comment.
Right now, we only support a single ordering for each type, so everything would use the "natural" ordering. Also, if the intent was to add named orderings later, I think it is unlikely that custom collations would make good method names. It wouldn't make sense to use some sanitized form of ISO-8859-1/en_US/primary, for example.
Your intent might have been to express the transform instead of the order, with "natural" meaning the identity transform?
In that case, it would look like this?
SortOrder.builderFor(schema)
.day("ts", DESC)
.bucket("id", 16)
.natural("id", DESC, NULLS_FIRST)
.build()Instead of using the order name for the method, what about using the direction? That would look like this:
SortOrder.builderFor(schema)
.desc(day("ts"))
.asc(bucket("ts", 16))
.desc("id", NULLS_FIRST)
.build();Another alternative is to use by:
SortOrder.builderFor(schema)
.by(day("ts"), DESC)
.by(bucket("ts", 16))
.by("id", DESC, NULLS_FIRST)
.build();I think it makes sense to express the sorted field as an expression so that we can use helper methods to create the sort order like this. What do you think?
| if ("identity".equalsIgnoreCase(transform)) { | ||
| return IdentityTransform.get(); | ||
| } else { | ||
| // TODO: consider UnknownSortTransform instead of throwing an exception |
There was a problem hiding this comment.
Yeah, we should do this for forward-compatibility.
| return builder.build(); | ||
| } | ||
|
|
||
| private static Map<Integer, SortOrder> indexSortOders(List<SortOrder> sortOrders) { |
There was a problem hiding this comment.
Typo: Oders instead of Orders
I think that an enum works best in a builder API, but enums are best for the metadata format and table metadata API. We want to avoid passing boolean options as config, but we do want to model the data in the API as tightly as possible. |
I'd like to reuse the existing |
Yeah, this is getting large. Maybe we should switch to a builder pattern for table creation as well, like this: catalog.newTable(TableIdentifier.of("db", "table"))
.addColumn("id", IntegerType.get())
.addColumn("ts", TimestampType.withZone())
.addColumn("data", StringType.get())
.partitionBy(day("ts"), bucket("id", 16))
.orderBy(day("ts"), bucket("id", 16), identity("id"))
.location("s3://bucket/warehouse/db.db/table")
.create()We could use actions |
|
I'll pick this up tomorrow |
| return false; | ||
| } | ||
|
|
||
| for (int fieldIndex = 0; fieldIndex < anotherSortOrder.fields.length; fieldIndex++) { |
There was a problem hiding this comment.
Nit: presumably using stream API makes code a bit more readable so I thought I'd suggest something like
return java.util.stream.IntStream
.range(0, Math.min(fields.size(), anotherSortOrder.fields.size()))
.anyMatch(i -> !fields.get(i).semanticEquals(anotherSortOrder.fields.get(i)))
| ImmutableMap.copyOf(properties), -1, ImmutableList.of(), ImmutableList.of()); | ||
| lastColumnId.get(), freshSchema, INITIAL_SPEC_ID, ImmutableList.of(freshSpec), INITIAL_SORT_ORDER_ID, | ||
| ImmutableList.of(freshSortOrder), ImmutableMap.copyOf(properties), -1, | ||
| ImmutableList.of(), ImmutableList.of()); |
There was a problem hiding this comment.
Nit: also, probably Collections.emptyList() fits best if immutability is the only requirement here, simply because of a JDK over library rationale
|
@aokolnychyi nice work! Maybe this is out of scope for a first cut implementation, but should we also add an API for |
|
@aokolnychyi Do you still work on this feature? |
|
To give an update, there is a proposal in Spark to extend Data Source V2 for clustering and sort on write. It would be great to have more feedback on that. The sort spec in Iceberg will look similar. |
|
I'll probably update this PR based on the current proposal even though it is not finalized. |
|
I am closing this in favor of PR #1373. |
This PR contains a very early preview of how we can extend Iceberg metadata with
SortOrder.The API currently looks like this:
The extended metadata looks like this:
Later, we can have something like this:
Open Questions:
DirectionandNullOrderas enums or convert them to booleans.TODOs:
TableMetadataoperations.sortColumnsfromDataFileand replace it withsortOrderId.This addresses #317.