The situation
Orders arrive as JSON and are stored with the line items nested inside each order. The finance team needs one summary row per customer that mixes two kinds of numbers: values that belong to the order (how many orders, what was charged for shipping) and values that belong to the items (units and item value).
Input tables
orders
One row per order.
| Column | Type | Description |
|---|---|---|
order_id |
BIGINT | Unique per order. |
customer_id |
BIGINT | The customer who ordered. |
shipping_fee |
DECIMAL(10,2) | Charged once per order. Can be 0.00. |
items |
ARRAY<STRUCT<sku: STRING, qty: INT, unit_price: DECIMAL(10,2)>> | The line items. Can be an empty array, and can be NULL. |
Run orders.printSchema() to see the nested structure.
Requirement
Return one row per customer.
ordersis the number of the customer's orders, whatever their items look like.shipping_totalis the sum ofshipping_feeover those orders. Each order's fee counts once.items_valueis the sum ofqtytimesunit_priceover all items of all the customer's orders.total_unitsis the sum ofqtyover those items.- An order with an empty or NULL
itemsarray still counts as an order and its shipping fee still counts. It adds nothing toitems_valueandtotal_units. - A customer whose orders have no items at all has
items_value= 0.00 andtotal_units= 0.
Expected output
One row per customer.
| Column | Type | Description |
|---|---|---|
customer_id |
BIGINT | |
orders |
BIGINT | Number of orders. |
items_value |
DECIMAL(14,2) | Sum of qty times unit_price. |
shipping_total |
DECIMAL(12,2) | Sum of shipping fees, once per order. |
total_units |
BIGINT | Sum of qty. |
Explanation
Show explanationGives the answer away. Try the problem first.
The approach
orders has one row per order. After explode("items") the DataFrame has one row per
item, and every order-level column is copied onto each of those rows. An order with
four items now has its shipping_fee four times.
That is the same thing a one-to-many join does (problem 1), without a join in sight. The rule is also the same: a value may only be summed at the grain it belongs to.
This report needs values at two grains, so it needs two aggregations:
# Order grain: one row per order, straight from the table.
order_level = orders.groupBy("customer_id").agg(
F.count("*").alias("orders"),
F.sum("shipping_fee").alias("shipping_total"),
)
# Item grain: one row per item, after the explode.
items = orders.select("customer_id", F.explode("items").alias("item"))
item_level = items.groupBy("customer_id").agg(
F.sum(F.col("item.qty") * F.col("item.unit_price")).alias("items_value"),
F.sum("item.qty").alias("total_units"),
)
Then join the two on customer_id, with order_level on the left. A customer whose
orders have no items is missing from item_level, so the item columns come back NULL
and are replaced with 0.
There are 118 orders from 25 customers. 5 orders have an empty items array and 4
have none at all.
Common wrong answers
Explode, then aggregate everything in one groupBy. Shipping is counted once per
item. The true shipping total across all orders is 6,518.00; summed after the explode
it is 16,249.00. count("*") counts items, not orders. And the result has 24 rows
instead of 25: customer 324's only order has an empty array, explode produces no row
for it, and the customer vanishes.
Fixing the count with countDistinct("order_id"). The order count is now right
for the orders that survive the explode, and shipping is still wrong. This is the
half-fix to watch for: one symptom is treated and the cause stays.
explode_outer instead of explode. explode_outer keeps orders with an empty
or NULL array, as one row with a NULL item. That brings customer 324 back, so the row
count is 25. Shipping is still summed once per item for every order with more than
one item. explode_outer fixes the lost rows; it does nothing about the repeated
ones.
Dividing shipping by the number of items. Spreading the fee across the item rows and summing it back can be made to work, but it breaks on orders with no items (a division by zero, or a lost fee) and on rounding. Aggregating at the right grain is simpler and exact.
Without an explode at all
Spark can also aggregate inside the array, with the higher-order function
F.aggregate, which computes one value per order from its items without changing
the number of rows. After that, every column is at the order grain and a single
groupBy is correct. A NULL array still gives NULL, so it needs a coalesce.
Edge cases in the data
| Case | Where | What it catches |
|---|---|---|
| Orders with more than one item | 71 of 118 orders | Shipping fee summed once per item. |
| Orders with exactly one item | 38 orders | These come out right either way, which hides the bug in small tests. |
Empty items array |
5 orders | explode drops the order and its shipping fee. |
NULL items |
4 orders | The same, and size(items) is not 0 for these. |
| Customer whose only order has no items | 324 | The customer disappears from the result. |
| One order without items, one with | 325 | The order count and the shipping total must include both. |