Repository navigation
API: Implement SortOrder - #1373
Conversation
| * @return a Table instance | ||
| * @throws AlreadyExistsException if the table already exists | ||
| */ | ||
| default Table createTable( |
There was a problem hiding this comment.
This seems to get out of hand. We may want to switch to a builder here.
There was a problem hiding this comment.
I think that would definitely make it a little cleaner here and in all of the related "create" methods
There was a problem hiding this comment.
@rdsr @shardulm94 @rdblue what do you guys think?
There was a problem hiding this comment.
I'm +1. But this is a public API, we'd have to keep the current methods around though, marked as deprecated.
There was a problem hiding this comment.
Yeah, I think we can map existing methods into the builder and keep the compatibility.
There was a problem hiding this comment.
We only double the number of implementations every time we add a new config option...
+1 to a builder, I think that would be helpful.
|
@rdblue @danielcweeks @RussellSpitzer @rdsr @shardulm94 @fbocse @prodeezy While I am working on tests and docs, this PR is ready for the first review round. |
| this.schema = schema; | ||
| } | ||
|
|
||
| public Builder asc(String name, NullOrder nullOrder) { |
There was a problem hiding this comment.
I did not default the null order as the SQL standard does not define this. Spark and Presto, as well as RDBMs, use different default null orderings.
There was a problem hiding this comment.
I think even if other frameworks don't define this it's ok to have a default? Like If a user doesn't care then we should just make the decision for them right?
There was a problem hiding this comment.
Yeah, I'll be fine with picking a default value ourselves.
There was a problem hiding this comment.
What does Presto use? That seems like a reasonable choice. I'd like to avoid requiring field-level NullOrder when using this API.
That might be slightly annoying, since the builder pattern shouldn't rely on calling methods in a particular order. That is, I think that these two should produce the same sort order:
// ORDER BY x ASC NULLS FIRST, y DESC NULLS FIRST
SortOrder.builderFor(schema)
.asc("x")
.desc("y")
.nullsFirst()
.build();
// ORDER BY x ASC NULLS FIRST, y DESC NULLS FIRST
SortOrder.builderFor(schema)
.nullsFirst()
.asc("x")
.desc("y")
.build();There was a problem hiding this comment.
Presto seems to behave differently than any other system. I wanted to follow Spark, Hive and MySQL until I saw a stale PR in Hive to switch to NULLS LAST by default. Having said that, I still propose to match Spark and MySQL and also allow setting a null order per column as that is possible in many systems.
There was a problem hiding this comment.
That sounds good to me for the defaults. I'd still like to make it easy to use the default if you don't care, and easy to set the default for this sort order, like the examples above.
There was a problem hiding this comment.
How commonly do we expect to see cases when users want to configure a null order for all columns through a global param? In most cases, the ordering will come from query engines in a form of expressions that have a null order per column. If users create a sort order manually and don't care, they can just skip null orders. I do get the use case of being able to set the default but my worry that it complicates the implementation. We will need to defer assigning a null order in asc/desc and iterate through sort columns in build and see whether we already assigned the null order for a particular column.
There was a problem hiding this comment.
Yeah, that's a fair argument. We can always add nullsFirst() and nullsLast() calls later and keep just the asc and desc calls for now.
There was a problem hiding this comment.
Presto does NULLS LAST by default in both directions because we expect that users don't want to see nulls. Consider these queries:
SELECT x FROM t ORDER BY x LIMIT 10;
SELECT x FROM t ORDER BY x DESC LIMIT 10;In both of these cases, the user likely wants to see some data, not a bunch of nulls. This behavior is allowed by the SQL standard:
If
<null ordering>is not specified, then an implementation-defined<null ordering>is implicit. The implementation-defined default for<null ordering>shall not depend on the context outside of<sort specification list>.
|
|
||
| public static NullOrder fromJsonValue(String jsonValue) { | ||
| Preconditions.checkArgument(jsonValue != null, "json value is null"); | ||
| return NullOrder.valueOf("NULLS_" + jsonValue.toUpperCase(Locale.ENGLISH)); |
There was a problem hiding this comment.
I've usually seen this with "Locale.ROOT" to avoid the Turkish issues, I assume English works as well?
There was a problem hiding this comment.
Yeah, should work too.
There was a problem hiding this comment.
Yeah, both work. I think we have mixed usage in the project. If the word is English, then it's okay to use this.
| } | ||
|
|
||
| // this ordering has either more or the same number of sort fields | ||
| return IntStream.range(0, anotherSortOrder.fields.length) |
There was a problem hiding this comment.
Could use guava Streams.zip here, skip a little bit of direct indexing but that's personal preference
There was a problem hiding this comment.
I'd rather not expand the use of Gauva. We could build our own zip easily enough.
There was a problem hiding this comment.
Let's keep it as is then.
|
|
||
| // determine the next order id | ||
| int maxOrderId = sortOrders.stream().mapToInt(SortOrder::orderId).max().orElse(INITIAL_SORT_ORDER_ID); | ||
| int nextOrderId = maxOrderId + 1; |
There was a problem hiding this comment.
This block of changes 652 -668 Is confusing to me, could add some more comments? I'm mostly confused about when we add "freshSortOrder" , it looks like we ignore it entirely if an equivalent SortOrder is there?
There was a problem hiding this comment.
I've matched the logic we have for PartitionSpec. If we have an equivalent partition spec, we use it. I'll add a comment.
There was a problem hiding this comment.
This is used when we are running a REPLACE TABLE operation. We want to keep the history, but the schema and partition spec can be completely new. When the schema and partition spec are new, we assign fresh IDs to the schema and rebuild the partition spec (and sort order) to use the newly assigned IDs. That's why we use the freshSpec and freshSortOrder methods here as well as when creating new table metadata -- because we don't trust the IDs that were assigned in the schema that was passed in.
I should note that when we update a schema, we also rebuild the specs and sort orders. But in those cases, the IDs aren't what we are changing. What may change are the fields in the schema. Fields could be renamed, or dropped. What we're primarily looking for is when a field is dropped. Then rebuilding the order or spec will hit a validation exception.
| @@ -35,6 +35,7 @@ | |||
| import org.apache.iceberg.TableMetadata.MetadataLogEntry; | |||
There was a problem hiding this comment.
Does this include tests for the serde to/from json?
There was a problem hiding this comment.
This also tests backward compatibility.
| .findAny(); | ||
| int orderId = sameSortOrder.map(SortOrder::orderId).orElse(nextOrderId); | ||
|
|
||
| ImmutableList.Builder<SortOrder> sortOrdersBuilder = ImmutableList.<SortOrder>builder().addAll(sortOrders); |
There was a problem hiding this comment.
This place, probably, requires additional attention. I've added a test to TestReplaceTransaction.
| import static org.apache.iceberg.NullOrder.NULLS_FIRST; | ||
| import static org.apache.iceberg.SortDirection.DESC; | ||
|
|
||
| public class TestSortOrderParser extends TableTestBase { |
There was a problem hiding this comment.
I will add more tests here.
|
I've added initial tests. |
| private SortOrder(Schema schema, int orderId, List<SortField> fields) { | ||
| this.schema = schema; | ||
| this.orderId = orderId; | ||
| this.fields = fields.toArray(new SortField[0]); |
There was a problem hiding this comment.
Nit: I find it a bit less awkward to use a stream for these cases because it accepts a factory method:
this.fields = fields.stream().toArray(SortField[]::new);There was a problem hiding this comment.
Actually, Intellij highlights this and suggests to replace with fields.toArray(new SortField[0]). I am ok with both options but would prefer to avoid extra warnings.
|
|
||
| TableMetadata metadata = TableMetadata.newTableMetadata( | ||
| schema, spec, baseLocation, properties == null ? Maps.newHashMap() : properties); | ||
| Map<String, String> tableProps = properties != null ? properties : ImmutableMap.of(); |
There was a problem hiding this comment.
Should we have defaults for sortOrder and spec as well? It seems strange that we do this for properties, but not the others.
There was a problem hiding this comment.
(Not something we need to decide in this PR)
There was a problem hiding this comment.
Yeah, I think that will be safe. Right now, we pass null for table properties in overloaded methods so we must handle it explicitly. But nothing prohibits a user from passing null for spec and sortOrder even though we properly default them in overloaded methods.
| generator.writeStartArray(); | ||
| for (SortField field : sortOrder.fields()) { | ||
| generator.writeStartObject(); | ||
| generator.writeStringField(TRANSFORM, field.transform().toString()); |
There was a problem hiding this comment.
Do we need to write a transform if it is identity? It would be nice to omit this when it is identity.
There was a problem hiding this comment.
I am ok omitting but it will add extra logic and it will behave differently compared to PartitionSpec.
|
|
||
| public int defaultSortOrderId() { | ||
| return defaultSortOrderId; | ||
| } |
There was a problem hiding this comment.
Should we also expose defaultSpecId directly? Normally, we use spec().specId().
There was a problem hiding this comment.
I am following what we have for specs to be consisent.
| String location, | ||
| Map<String, String> properties) { | ||
| return newTableMetadata(schema, spec, location, properties, DEFAULT_TABLE_FORMAT_VERSION); | ||
| return newTableMetadata(schema, spec, SortOrder.unsorted(), location, properties, DEFAULT_TABLE_FORMAT_VERSION); |
There was a problem hiding this comment.
This class might be a good one for a builder as well...
| } | ||
| sortOrders = sortOrdersBuilder.build(); | ||
| } else { | ||
| SortOrder defaultSortOrder = SortOrder.unsorted(); |
There was a problem hiding this comment.
Minor: This variable doesn't seem necessary.
There was a problem hiding this comment.
That var is used in two lines below, I think it is a bit easier to read if we preassign it.
|
I've not gone though the tests thoroughly yet, but the implementation looks great to me. Unfortunately, I think there's a major problem with adding sort orders: what if an older writer rewrites table metadata and drops the sort order list? For example, if I have a table that is sorted by Erasing the sort order is an annoyance right now. But if we use the sort order for delete files and data files, then this could turn into a correctness problem. Say a table has a data file sorted by I can think of two solutions. First, we could add sort orders to v1, but require them for v2 like we do for the partition spec list. That way, all v2 writers will guarantee that sort orders are not dropped and we no longer have a problem. The second option is to assign sort order IDs using a hash so two orders would not collide. I think I prefer the first option. Thoughts? |
|
Would it make sense to store the sort order in the file (as part of attributes / metadata) as a safety check? |
Yes, we should definitely do this. |
|
@electrum, yes, there will be at least 3 follow-up items I noted in the PR description:
|
| } | ||
| sortOrders = sortOrdersBuilder.build(); | ||
| } else { | ||
| SortOrder defaultSortOrder = SortOrder.unsorted(); |
There was a problem hiding this comment.
If the SortOrder list is required by v2, then I think that we should add a check here that the table is v1. That way, we fail to read a table and force recovery if a v2 table doesn't have an order list.
We should probably also update the PartitionSpec logic above to do the same thing.
There was a problem hiding this comment.
I tried that but we need to adapt tests. So, I've created #1419 to address this in a follow-up.
|
+1 overall. We can either add the v2 check in this PR or later. |
de19ccb to
4e0501c
Compare
4e0501c to
edbddb2
Compare
|
I've merged this PR to get this feature going. I keep the original issue open since this work is not complete. Follow-up items:
|
|
Is this note in the documentation still accurate?
|
Co-authored-by: Szehon Ho <[email protected]>
This PR extends Iceberg metadata with a sort order and is supposed to replace the work in #589.
The API currently looks like this:
The underlying representation looks like this:
Open items
Catalog.Terms inBuilder.Follow-up items