Skip to content

[WIP] Extend metadata with SortOrder - #589

Closed
aokolnychyi wants to merge 1 commit into
apache:masterfrom
aokolnychyi:sort-order
Closed

aokolnychyi wants to merge 1 commit into
apache:masterfrom
aokolnychyi:sort-order

Conversation

@aokolnychyi

@aokolnychyi aokolnychyi commented Oct 29, 2019 •

Copy link
Copy Markdown
Contributor

This PR contains a very early preview of how we can extend Iceberg metadata with SortOrder.

The API currently looks like this:

SortOrder.builderFor(schema)
    .natural("col1")
    .natural("col2", ASC, NULLS_FIRST)
    .build()

The extended metadata looks like this:

  "default-sort-order-id" : 0,
  "sort-orders" : [ {
    "order-id" : 0,
    "fields" : [ {
      "name" : "id",
      "direction" : "desc",
      "null-order" : "nulls_last",
      "transform" : "identity",
      "source-ids" : [ 1 ]
    }, {
      "name" : "data",
      "direction" : "asc",
      "null-order" : "nulls_first",
      "transform" : "identity",
      "source-ids" : [ 2 ]
    } ]
  } ],

Later, we can have something like this:

  "default-sort-order-id" : 3,
  "sort-orders" : [ {
    "order-id" : 3,
    "fields" : [ {
      "name" : "zvalue",
      "direction" : "asc",
      "null-order" : "nulls_first",
      "transform" : "zorder(8, 16)",
      "source-ids" : [ 1, 4 ]
    } ]
  } ],

Open Questions:

  • Overall approach (any ideas are welcome).
  • Whether we need to have the actual logic for sort transformations in Iceberg or in query engines. The current implementation assumes that query engines will simply report the ordering of incoming data. Another way is to have sort transformations in Iceberg and register them in query engines (e.g. function catalog), but it might be tricky for query engines to report that ordering back to Iceberg on writes. Moreover, all query engines have their internal memory format and we want to avoid the cost of serializing data to Java objects to simply perform the sorting step. Having sort transformations in Iceberg will be needed if we have to sort diff files for row-level updates in Iceberg rather than rely on the existing ordering.
  • Whether to keep Direction and NullOrder as enums or convert them to booleans.
  • Avoid major changes in the Catalog API. It is not a good idea to break the existing API but I am not sure generating that many methods is worth it. Maybe, we can simply reduce the number of overloaded methods that were added by this commit.

TODOs:

  • Handle the sort order in all TableMetadata operations.
  • Propagate the sort order to files and annotate each file with orderId.
  • Remove sortColumns from DataFile and replace it with sortOrderId.
  • API for updating the sort order in a table.
  • It looks like query engines will have to report the ordering of data before writing. Then we will need to propagate this info to files.
  • Document changes to the format.

This addresses #317.

import java.util.Objects;
import org.apache.iceberg.SortTransforms.SortTransform;

public class SortField implements Serializable {

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.

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

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.

Why include a name?

return sourceIds;
}

public boolean semanticEquals(SortField that) {

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 about sameOrder?

// TODO: toString()
public class SortOrder implements Serializable {

private static final SortOrder UNSORTED_ORDER = new SortOrder(new Schema(), 0, ImmutableList.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.

Does this mean that order ID 0 is reserved for the unsorted order?

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: 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++) {

@rdblue rdblue Nov 10, 2019 •

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

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 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.

@aokolnychyi aokolnychyi Nov 26, 2019 •

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 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?

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.

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?

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

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.

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?

@aokolnychyi aokolnychyi Dec 11, 2019 •

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.

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.

@aokolnychyi aokolnychyi Dec 13, 2019 •

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 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?

@aokolnychyi aokolnychyi Dec 13, 2019 •

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.

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.

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 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.

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

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.

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

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, we should do this for forward-compatibility.

return builder.build();
}

private static Map<Integer, SortOrder> indexSortOders(List<SortOrder> sortOrders) {

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.

Typo: Oders instead of Orders

@rdblue

rdblue commented Nov 10, 2019

Copy link
Copy Markdown
Contributor

Whether to keep Direction and NullOrder as enums or convert them to booleans

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.

@rdblue

rdblue commented Nov 10, 2019

Copy link
Copy Markdown
Contributor

Whether we need to have the actual logic for sort transformations in Iceberg or in query engines.

I'd like to reuse the existing Transform classes, if possible. It would also be nice to add transforms to the Expressions API so that we can pass an expression, like bucket("id", 16), into the sort order builders.

@rdblue

rdblue commented Nov 10, 2019

Copy link
Copy Markdown
Contributor

Avoid major changes in the Catalog API

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 create, createTransation, replaceTransaction, and createOrReplaceTransaction instead of separate methods.

@rdblue rdblue mentioned this pull request Dec 4, 2019
@aokolnychyi

Copy link
Copy Markdown
Contributor Author

I'll pick this up tomorrow

return false;
}

for (int fieldIndex = 0; fieldIndex < anotherSortOrder.fields.length; fieldIndex++) {

@fbocse fbocse Jan 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.

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

@fbocse fbocse Jan 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.

Nit: also, probably Collections.emptyList() fits best if immutability is the only requirement here, simply because of a JDK over library rationale

@prodeezy

prodeezy commented Apr 8, 2020

Copy link
Copy Markdown
Contributor

@aokolnychyi nice work!

Maybe this is out of scope for a first cut implementation, but should we also add an API for SortOrder evolution? Something like UpdateSortOrder? So that changes to sort order can be validated, controlled & audited within this API. This API can be accessed using Table.updateSortOrder() maybe?

@yiguolei

Copy link
Copy Markdown

@aokolnychyi Do you still work on this feature?

@aokolnychyi

Copy link
Copy Markdown
Contributor Author

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.

@aokolnychyi

Copy link
Copy Markdown
Contributor Author

I'll probably update this PR based on the current proposal even though it is not finalized.

@aokolnychyi

Copy link
Copy Markdown
Contributor Author

I am closing this in favor of PR #1373.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants