All six orders stay. Each one gets the total of its customer. With groupBy you would get only four rows.
orderBy inside the window sorts the rows of each window. Ranking, lag and running totals need it.
Spark must bring the rows of one window together, so a window step shuffles by the partitionBy column (chapter 5).
Watch out
A window with orderBy but no partitionBy puts every row into one partition. Spark warns about it in the log. That is fine for 6 orders, but one task cannot hold a billion rows.
03 · Ranking
Ranking: row_number, rank & dense_rank
⏱ 6 min · Topic 3 of 5
Three functions number the rows in order. They agree until two rows tie. The order items have a tie: five items have quantity 1.
row_number gives every row a different number. rank and dense_rank give tied rows the same number.
Here rank and dense_rank agree. After a tie, rank skips numbers and dense_rank does not. A sixth item with quantity 0 would get rank 8 but dense_rank 4.
Among the tied rows, row_number picks an order you cannot predict. Add a second sort column, such as order_id, to fix it.
Keep the newest row per key
Chapter 8 said dropDuplicates keeps any one row. To keep the newest order of each customer every time, number the rows newest first and keep number 1:
The first order of each customer has no row before it, so previous is NULL.
A running total adds up all rows from the start to the current row. The frame says which rows count. rowsBetween(Window.unboundedPreceding, Window.currentRow) means: from the first row up to this one.
40.0, then 40.0 + 25.0, and so on. The last row holds the total of all paid orders, 160.5.
Without rowsBetween, the default frame counts by value, not by row. Two orders on the same day would then share one running total. Give the frame yourself.
05 · Next Chapter
Next Chapter
You can now rank, compare and add up rows inside a window.
⏱ 3 min · Topic 5 of 5
Next chapter
Spark SQL & the Catalyst Optimizer
You can now rank, compare and add up rows inside a window.
Next, you see how Spark turns all these steps into a plan, and how its optimizer makes the plan faster.