Sub topic 6
Co-locating data with Z-ordering
Compaction fixes the number of files, but it does not decide which rows go into which file. This chapter covers Z-ordering, which rewrites files so that rows with similar values in chosen columns end up together. It assumes you know what OPTIMIZE does, how Delta stores min/max statistics per file, and how Hive-style partitioning works, all from earlier chapters.
The problem Z-ordering solves
Data skipping works by comparing a query's filter against the minimum and maximum value of each column in each file. If a file's range for user_id is 1 to 9,000,000 and you filter on user_id = 42, the file cannot be skipped, because 42 falls inside its range.
Rows usually arrive in time order, not in user_id order. Every file therefore holds a wide spread of user IDs, and the ranges overlap almost completely. Compaction alone makes this no better. It produces fewer, larger files, but each one still contains a mix of users.
Z-ordering rewrites the data so that each file covers a narrow range of the chosen columns. The ranges then overlap far less, and a filter can rule out most files from the statistics alone.
| Layout | File 1 range of `user_id` | File 2 range | File 3 range | Files read for `user_id = 42` |
|---|---|---|---|---|
| Arrival order | 1 to 9,000,000 | 3 to 8,999,000 | 2 to 9,000,000 | 3 of 3 |
| After Z-order | 1 to 3,000,000 | 3,000,001 to 6,000,000 | 6,000,001 to 9,000,000 | 1 of 3 |
How the Z-order curve works
For a single column, co-locating is just sorting. The harder case is several columns, such as user_id and event_date. Sorting by one column and then the other would favor the first column. It would give tight ranges for user_id and almost no benefit for event_date.
Z-ordering uses a space-filling curve. It converts each column value to a rank, interleaves the bits of the ranks into one number, and sorts the rows by that number. Rows that are close in every column tend to get close Z-values, so they land in the same file. The effect is a compromise: each column gets reasonable ranges, and none gets perfect ones.
Running Z-ordering
Z-ordering is an option of OPTIMIZE. It compacts files and clusters rows in the same pass. The tutorial's partitioned table is a good example:
CREATE TABLE events_partitioned (
event_id BIGINT,
user_id BIGINT,
event_date DATE,
payload STRING
)
PARTITIONED BY (event_date);
OPTIMIZE events_partitioned
WHERE event_date >= '2024-01-01'
ZORDER BY (user_id);The WHERE clause may reference only partition columns. It limits the rewrite to recent partitions, so you do not reshuffle years of cold data. Each partition is Z-ordered on its own, and rows never move between partitions.
The same operation is available from Python:
from delta.tables import DeltaTable
dt = DeltaTable.forName(spark, "events")
dt.optimize().executeCompaction()
dt.optimize().executeZOrderBy("user_id")To restrict the Python version to some partitions, call .where("event_date >= '2024-01-01'") on the optimize builder before executeZOrderBy.
You can list several columns, as in ZORDER BY (user_id, country). Separate the names with commas inside the parentheses.
What it costs
Z-ordering is more expensive than plain compaction, and the reasons are worth knowing before you schedule it.
- It is a full rewrite. Compaction can merge only small files. Z-ordering must shuffle and sort the rows of every file it touches, so it uses more cluster time and I/O.
- It is not fully incremental. If no new data has arrived in a partition since the last Z-order, running it again does nothing. When new data arrives, Delta aims to avoid reprocessing everything, but the time of repeated runs is not guaranteed to shrink. Plan for each run to touch at least the new and recently changed data.
- It must be rerun. Z-ordering applies to the files that exist when you run it. New writes arrive unsorted, and the layout drifts until the next
OPTIMIZE ... ZORDER BY. A scheduled job is the usual pattern. - It leaves old files behind. Rewritten files are removed from the transaction log but stay in storage until
VACUUMdeletes them. That is covered in a later chapter.
Limits and gotchas
Z-order columns need statistics
Data skipping only helps for columns that have statistics. By default, Delta collects statistics on the first 32 columns of the table. If a Z-order column falls beyond that, the rewrite clusters the data, but queries cannot exploit it. Put frequently filtered columns early in the schema, or raise delta.dataSkippingNumIndexedCols. Long strings are a related trap, because statistics on them are truncated.
You cannot Z-order by a partition column
Partition columns already segregate files by value, so Delta rejects them in ZORDER BY. Choose a different column.
Effectiveness drops as you add columns
Each extra column dilutes the locality of the others. One or two columns work well. Four or five give weak skipping on all of them. List only the columns that your queries filter on most often.
Low-cardinality columns gain little
A column with a handful of distinct values, such as a status flag, is already easy to skip on if its values cluster. The best Z-order candidates have many distinct values and appear in selective filters, like user_id or device_id.
It does not help queries that do not filter
A full scan, or a filter on a column you did not Z-order, reads the same files as before. Z-ordering also does not help joins or aggregations by itself, except where a filter on a Z-ordered column reduces the files read.
It is superseded on newer tables
Z-ordering cannot be combined with liquid clustering. On a table that uses CLUSTER BY, you run plain OPTIMIZE instead. The next chapter covers liquid clustering, which keeps the same goal without a separate ZORDER BY clause.
Confirming it worked
Check the result instead of assuming it. After the run, inspect the history and the file counts:
DESCRIBE HISTORY events_partitioned;
DESCRIBE DETAIL events_partitioned;In DESCRIBE HISTORY, the OPTIMIZE row shows the zOrderBy columns in its operation parameters. Its metrics show how many files were added and removed. The measure that matters is the query itself. Run a selective query before and after, and compare the number of files read and the bytes scanned in the query profile or Spark UI. A successful Z-order shows far fewer files read for the same filter. If the number barely moves, the column probably lacks statistics, has low selectivity, or is not the column the query filters on.
When to choose it
Z-ordering suits an existing partitioned table where a few high-cardinality columns are filtered often, and where you can afford a periodic rewrite. It gives a large benefit for a small configuration cost. It becomes awkward when filter columns change over time, because each change means a different ZORDER BY and a different rewrite. It also becomes awkward when tables are large enough that repeated rewrites are costly. Those are the cases that liquid clustering addresses.
Exercise
A table events_partitioned is partitioned by event_date. Queries filter on user_id = 42 and scan almost every file, although OPTIMIZE already ran last night. Write the statement that rewrites only partitions from 2024-01-01 onward to improve skipping for these queries, and explain why plain OPTIMIZE did not help.
Show answer
Run OPTIMIZE events_partitioned WHERE event_date >= '2024-01-01' ZORDER BY (user_id);. Plain OPTIMIZE only merges small files. Each file still holds a wide spread of userid values, so the min/max ranges overlap and no file can be skipped. Z-ordering rewrites the rows so each file covers a narrow userid range.
Exercise
You run OPTIMIZE events_partitioned ZORDER BY (event_date) and get an error. Why does it fail, and what should you do?
Show answer
eventdate is the partition column. Delta does not allow Z-ordering by partition columns, because partitioning already separates files by that value. Choose a non-partition column that queries filter on, such as userid.
Exercise
After Z-ordering by user_id, a query filtering on user_id still reads nearly all files. Name two likely causes.
Show answer
Possible causes: user_id is beyond the first 32 columns and has no statistics (fix by reordering the schema or raising delta.dataSkippingNumIndexedCols); the filter is not selective, or new data has arrived since the last Z-order and the layout has drifted, so OPTIMIZE ZORDER BY needs to run again.