Skip to content

API: Implement SortOrder - #1373

Merged
aokolnychyi merged 2 commits into
apache:masterfrom
aokolnychyi:sort-spec-impl
Sep 4, 2020
Merged

aokolnychyi merged 2 commits into
apache:masterfrom
aokolnychyi:sort-spec-impl

Conversation

@aokolnychyi

@aokolnychyi aokolnychyi commented Aug 24, 2020 •

Copy link
Copy Markdown
Contributor

This PR extends Iceberg metadata with a sort order and is supposed to replace the work in #589.

The API currently looks like this:

SortOrder.builderFor(schema)
    .withOrderId(3)
    .asc("y", NullOrder.NULLS_FIRST)
    .desc(Expressions.bucket("z", 4), NullOrder.NULLS_LAST)
    .build();

The underlying representation looks like this:

   "default-sort-order-id": 3,
   "sort-orders": [
      {
         "order-id": 3,
         "fields": [
            {
               "transform": "identity",
               "source-id": 2,
               "direction": "asc",
               "null-order": "nulls-first"
            },
            {
               "transform": "bucket[4]",
               "source-id": 3,
               "direction": "desc",
               "null-order": "nulls-last"
            }
         ]
      }
   ],

Open items

  • Consider switching to a builder patter in Catalog.
  • Whether to reserve id 0 for the unsorted order.
  • Case sensitivity when binding Terms in Builder.

Follow-up items

  • Associate data and delete files with sort order id.
  • Spec update.
  • An API for updating the current sort order in a table.

* @return a Table instance
* @throws AlreadyExistsException if the table already exists
*/
default Table createTable(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems to get out of hand. We may want to switch to a builder here.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that would definitely make it a little cleaner here and in all of the related "create" methods

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rdsr @shardulm94 @rdblue what do you guys think?

@rdsr rdsr Aug 28, 2020 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm +1. But this is a public API, we'd have to keep the current methods around though, marked as deprecated.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I think we can map existing methods into the builder and keep the compatibility.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@aokolnychyi aokolnychyi Sep 1, 2020 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Submitted PR #1409 for this.

@aokolnychyi

Copy link
Copy Markdown
Contributor Author

@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) {

@aokolnychyi aokolnychyi Aug 24, 2020 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I'll be fine with picking a default value ourselves.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@electrum electrum Sep 2, 2020 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've usually seen this with "Locale.ROOT" to avoid the Turkish issues, I assume English works as well?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, should work too.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could use guava Streams.zip here, skip a little bit of direct indexing but that's personal preference

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me check.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd rather not expand the use of Gauva. We could build our own zip easily enough.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've matched the logic we have for PartitionSpec. If we have an equivalent partition spec, we use it. I'll add a comment.

@rdblue rdblue Aug 29, 2020 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this include tests for the serde to/from json?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This also tests backward compatibility.

.findAny();
int orderId = sameSortOrder.map(SortOrder::orderId).orElse(nextOrderId);

ImmutableList.Builder<SortOrder> sortOrdersBuilder = ImmutableList.<SortOrder>builder().addAll(sortOrders);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will add more tests here.

@aokolnychyi

Copy link
Copy Markdown
Contributor Author

I've added initial tests.

@aokolnychyi aokolnychyi changed the title [WIP] API: Implement SortOrder API: Implement SortOrder Aug 26, 2020
private SortOrder(Schema schema, int orderId, List<SortField> fields) {
this.schema = schema;
this.orderId = orderId;
this.fields = fields.toArray(new SortField[0]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we have defaults for sortOrder and spec as well? It seems strange that we do this for properties, but not the others.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(Not something we need to decide in this PR)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've created #1411.

generator.writeStartArray();
for (SortField field : sortOrder.fields()) {
generator.writeStartObject();
generator.writeStringField(TRANSFORM, field.transform().toString());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to write a transform if it is identity? It would be nice to omit this when it is identity.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am ok omitting but it will add extra logic and it will behave differently compared to PartitionSpec.


public int defaultSortOrderId() {
return defaultSortOrderId;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we also expose defaultSpecId directly? Normally, we use spec().specId().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This class might be a good one for a builder as well...

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Created #1412.

}
sortOrders = sortOrdersBuilder.build();
} else {
SortOrder defaultSortOrder = SortOrder.unsorted();

@rdblue rdblue Aug 29, 2020 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: This variable doesn't seem necessary.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That var is used in two lines below, I think it is a bit easier to read if we preassign it.

@rdblue

rdblue commented Aug 29, 2020

Copy link
Copy Markdown
Contributor

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 id ASC NULLS FIRST, that would get sort order ID 0. If an older client writes, then that gets erased and the next reader assumes that the table is unordered.

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 id ASC NULLS FIRST and labelled with sort_order_id = 0 in manifests. When the sort order gets erased or replaced, there is no longer any tracking for what ID 0 meant. If I then add an unsorted equality delete file it may also get sort_order_id = 0 in its metadata. Then it would appear that the deletes can be merged instead of using a delete set because the order matches between the data file and the delete file when it actually does not.

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?

@rdblue rdblue added this to the Format Version 2 milestone Aug 29, 2020
@electrum

electrum commented Sep 2, 2020

Copy link
Copy Markdown
Contributor

Would it make sense to store the sort order in the file (as part of attributes / metadata) as a safety check?

@rdblue

rdblue commented Sep 2, 2020

Copy link
Copy Markdown
Contributor

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.

@aokolnychyi

Copy link
Copy Markdown
Contributor Author

@electrum, yes, there will be at least 3 follow-up items I noted in the PR description:

  • Associate data and delete files with sort order id.
  • Spec update.
  • An API for updating the current sort order in a table similar to what we have for partition specs.

}
sortOrders = sortOrdersBuilder.build();
} else {
SortOrder defaultSortOrder = SortOrder.unsorted();

@rdblue rdblue Sep 3, 2020 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tried that but we need to adapt tests. So, I've created #1419 to address this in a follow-up.

@rdblue

rdblue commented Sep 3, 2020

Copy link
Copy Markdown
Contributor

+1 overall. We can either add the v2 check in this PR or later.

@aokolnychyi
aokolnychyi merged commit 454101c into apache:master Sep 4, 2020
@aokolnychyi

Copy link
Copy Markdown
Contributor Author

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:

@haydenflinner

Copy link
Copy Markdown

Is this note in the documentation still accurate?

Explicit sort is necessary because Spark doesn’t allow Iceberg to request a sort before writing as of Spark 3.0. SPARK-23889 is filed to enable Iceberg to require specific distribution & sort order to Spark.

parthchandra pushed a commit to parthchandra/iceberg that referenced this pull request Oct 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants