groupBy and agg, multiple aggregations, rollup and cube, and pivot tables at scale.
⏱ 4 min readTopics chapter readerLevel · Structured APIs
01 · Overview
Start here
⏱ 4 min · Topic 1 of 7
To aggregate is to turn many rows into one number, such as a count or a sum. groupBy does it once for each group, such as each customer.
You already know the idea from the SQL chapters (GROUP BY). This chapter shows the same work with DataFrames, on the shop orders.
groupBy moves rows between tasks, so it is a wide step with a shuffle. Spark first adds up inside each task, then sends only those partial results (chapter 5).
02 · Group
groupBy + agg
⏱ 6 min · Topic 2 of 7
groupBy names the groups. agg says what to compute for each group:
The pending group has one order with no amount. So sum, avg and max have nothing to use, and they give NULL.
Look at the paid row. avg is 160.5 / 4 = 40.125, and round(..., 2) gives 40.13, because Spark rounds a half up. countDistinct counts different customers: Asha, Carla and Dev.
when inside sum gives several totals side by side, also in one pass:
Two rows say NULL in country. The first is Dev, whose country is missing. The last is the grand total.
grouping("country") tells them apart: it is 1 on the total row and 0 on a real group. Without it, a report cannot show which NULL is the total.
With two columns, rollup("country", "status") adds a subtotal for each country and one grand total: 10 rows here. cube adds every mix of subtotals: 13 rows. The SQL chapter Sets, Pivots & Reshaping Results explains the counts.
05 · Reshape
pivot: rows to columns
⏱ 4 min · Topic 5 of 7
pivot turns the values of one column into column names. Here each status becomes a column: