Joins and aggregations

Part of the free LogicWiz Data Engineering course, Module 11: PySpark DataFrames. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 11:40 on Wednesday. Tess's new report, revenue by payment method, is your first PySpark job with a join. It says cards brought in $2,826.76. The same orders, added up from their order lines alone, come to $2,735.51. The job ran without an error, and the gap is exactly $91.25.

You'll learn to

  • Group rows with groupBy().agg() and name every result
  • Pick the join key and type, including left_semi and left_anti
  • Spot a join that multiplies rows, and aggregate first to fix it
  • Predict what null keys do to joins, sums and shuffles

Learn

Start with one row per order

The report starts from the order lines: one row per product in an order. Money per order comes first, so you group.

df.groupBy('a', 'b').agg(...) is SQL's GROUP BY a, b, with the aggregates you list. Each one is an expression from F: F.count('*'), F.sum('qty'), F.avg(...), F.min(...), F.max(...), F.countDistinct('customer_id').

Two habits save pain:

  • Name every aggregate with .alias(). Otherwise Spark invents a name like sum(qty), awkward in the next step.
  • Say the grain out loud (Module 5). After groupBy('order_id'), one row means one order.

df.groupBy('status').count() is a shortcut that adds a column called count.

From order lines to orders

from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.getOrCreate()
items = spark.read.csv("data/order_items.csv", header=True, inferSchema=True)

lines = items.withColumn("line_amount", F.col("qty") * F.col("unit_price"))
per_order = lines.groupBy("order_id").agg(
    F.count("*").alias("lines"),
    F.sum("qty").alias("units"),
    F.round(F.sum("line_amount"), 2).alias("revenue"),
)
print("line rows:", lines.count(), " order rows:", per_order.count())
for r in per_order.orderBy("order_id").limit(3).collect():
    print(r["order_id"], r["lines"], r["units"], r["revenue"])

Every aggregate has a name from .alias(), so the next step can say F.col("revenue").

The grain changes: lines in, orders out

Before: orderidlinenoqtylineamountAfter: orderidlinesunitsrevenue
10031358.5
100322108.0100325166.5
10011 to 41 each126.49 in all100144126.49

201 line rows become 79 order rows. Order 1058 has no lines, so it has no row here at all: aggregating the lines can never tell you about orders that have none. That takes a join from the orders side.

Filter before or after the group

filter before groupByfilter after agg
Works like SQL WHEREWorks like SQL HAVING
Removes rows before they are countedRemoves whole groups, because each row is now a group
orders.filter(F.col('status') != 'cancelled').groupBy('customerid')...agg(F.count('').alias('orders')).filter(F.col('orders') = 3)
One row here means one orderOne row here means one customer

How a group-by runs on many machines

Tess also wants revenue per country. On a cluster, the lines of one country sit in many partitions on many machines. Sending every row to one place to add up would push a billion rows over the network. Spark works in three steps instead:

  1. Partial aggregate. Each task sums its own rows into a hash map, a lookup table from key to running total, so it sends at most one row per group.
  2. Shuffle. Those partial rows move across the network so that all rows of one key meet in one task. Moving rows by key like this is called a shuffle.
  3. Final aggregate. Each task adds up the partial sums for its keys.

Step through it with made-up numbers.

Revenue per country, three tasks at a time

Seven order lines from Canada and Spain sit in three tasks; each task sums its own rows, five partial sums are shuffled so each country meets in one task, and the final sums are 55 and 40 dollars.

  1. The rows where they were read. Seven order lines, $95 in all, spread over three tasks. Canada and Spain both show up in more than one task.

  2. Partial aggregate. Each task adds up its own rows by country, in a hash map. Seven rows become five partial sums, and nothing has moved yet.

  3. The shuffle. Each partial sum travels to the task that owns its key: Canada to one task, Spain to the other. Five small rows cross the network.

  4. Final aggregate. Each task adds the partial sums it received: Canada $55, Spain $40. Two rows out, $95 in all, the same money as the seven rows in.

Follow Canada: it starts in tasks 0 and 2 and ends in one task. On a real cluster a shuffle has 200 finishing tasks by default (spark.sql.shuffle.partitions).

Remember: each task sums its own rows before the shuffle. A sum over a billion rows moves only tasks x groups partial sums across the network.

Joins: which key, and which kind

Next the report needs each order's payment method, which lives in another table. left.join(right, on, how) joins two DataFrames.

  • on a column name (or a list of names) when both sides call the key the same thing: lines.join(orders, 'order_id'). Spark keeps one copy of the key column.
  • on an expression when the names differ: orders.join(people, orders.customer_id == people.id). Both key columns stay, so drop one afterwards.

how picks the join type: 'inner' (the default), 'left', 'right', 'full', and two you will use a lot in pipelines. A semi join, 'left_semi', keeps the left rows that have a match. An anti join, 'left_anti', keeps the ones that do not.

Join types and their SQL twins

howKeepsSQL twin
innerrows with a match on both sidesJOIN
leftevery left row; right columns are null where nothing matchedLEFT JOIN
fullevery row from both sidesFULL OUTER JOIN
leftsemileft rows that have a match; left columns only; never repeats a rowWHERE EXISTS (...)
leftantileft rows with no match; left columns onlyWHERE NOT EXISTS (...)

A null key never matches anything, in any join type, exactly as in SQL.

Revenue per country, and who never ordered

from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.getOrCreate()
items = spark.read.csv("data/order_items.csv", header=True, inferSchema=True)
orders = spark.read.csv("data/orders.csv", header=True, inferSchema=True)
customers = spark.read.csv("data/customers.csv", header=True, inferSchema=True)

lines = items.withColumn("line_amount", F.col("qty") * F.col("unit_price"))
by_country = (
    lines
    .join(orders, "order_id")
    .join(customers.select("customer_id", "country"), "customer_id")
    .groupBy("country")
    .agg(
        F.countDistinct("order_id").alias("orders"),
        F.round(F.sum("line_amount"), 2).alias("revenue"),
    )
    .orderBy(F.desc("revenue"), "country")
)
for r in by_country.limit(3).collect():
    print(r["country"], r["orders"], r["revenue"])

never = customers.join(orders, "customer_id", "left_anti")
print("never ordered:", sorted(r["customer_id"] for r in never.collect()))

customers.select("customer_id", "country") keeps only the columns the join needs. Both tables have an updated_at column, and carrying two columns with the same name through a join is asking for trouble.

The clue: order 1033 was paid twice

Back to the $91.25. An order can have more than one payment. At SwiftKart, order 1012 failed on a card and then succeeded with a wallet, returned orders have a capture and a refund, and order 1033 was captured twice on the same card, a minute apart.

Now join order lines to payments on order_id. Every line of an order meets every payment of that order. A key that repeats on the right repeats the left rows: Module 2 called this a fan-out. Nothing fails. The sum is too big, and that is all.

Order 1033's two lines add up to $91.25. Guess what the join does with them.

Order 1033 meets its payments

Order 1033 has two lines worth 65.00 and 26.25 and two captured card payments; the join pairs every line with every payment, making four rows worth 182.50, and grouping the payments to one row first gives two rows worth 91.25.

  1. Two lines, two payments. Order 1033 is $65.00 plus 3 x $8.75 = $26.25, so $91.25. The store captured that amount twice.

  2. Line 1 meets both payments. The key matches twice, so line 1 comes out twice: once beside 5037, once beside 5038.

  3. Line 2 does the same. Four rows now. Summed by method, card revenue for this one order is $182.50: $91.25 too much, the exact gap in Tess's report.

  4. The fix: one row per key first. Group the payments to one row per order and method, then join. Each line meets one payment row: two rows, $91.25.

Watch the right-hand box: it doubles in step 3 and shrinks back in step 4.

The trap: trusting a join to keep the row count. A join on a key that repeats on the right side multiplies rows without a word, even a left join, and every sum after it is wrong while the code runs without an error. Count rows before and after every join while you develop, and in production check that the key is unique on the side you expect (Module 7 automates this).

Watch the fan-out, then fix it

from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.getOrCreate()
items = spark.read.csv("data/order_items.csv", header=True, inferSchema=True)
payments = spark.read.json("data/payments.jsonl")

lines = items.withColumn("line_amount", F.col("qty") * F.col("unit_price"))
joined = lines.join(payments, "order_id")
print("line rows:", lines.count(), " after joining payments:", joined.count())
print("revenue from lines:", lines.agg(F.round(F.sum("line_amount"), 2).alias("r")).first()["r"])
print("revenue after join:", joined.agg(F.round(F.sum("line_amount"), 2).alias("r")).first()["r"])

# The fix: one row per order on both sides, then join
per_order = lines.groupBy("order_id").agg(F.round(F.sum("line_amount"), 2).alias("revenue"))
paid = (payments.filter(F.col("status") == "captured")
        .groupBy("order_id").agg(F.round(F.sum("amount"), 2).alias("paid")))
both = per_order.join(paid, "order_id", "left")
print("orders:", per_order.count(), " after the join:", both.count())

The first join turns 201 lines into 216 rows and adds $785.41 of revenue that does not exist. The fix brings both sides to one row per order before they meet.

Watch a join multiply rows

Two small tables, order lines and payments; choose the join key and watch every line repeat once for each payment of its order.

Pick a join type and watch order 1012 repeat, then tick the fix to add up the payments per order before the join.

Before you ship: null keys never meet

One more surprise. Spark follows SQL's rules for null, and each one shows up in pipelines:

  • Joins. a.k == b.k is null, never true, when either side is null, so null keys never match. For an inner join, the optimiser even adds isnotnull(k) filters on both sides before the shuffle. To match null with null on purpose, use a.k.eqNullSafe(b.k) (SQL's <=>).
  • Aggregates skip nulls, except count('*'). count('amount') counts the non-null values, avg divides by that count, and the sum of only nulls is null, not 0.
  • groupBy puts every null key into one group.

Null keys and null amounts, measured

from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder.getOrCreate()
left = spark.createDataFrame([(1, "a"), (2, "b"), (None, "c")], "k INT, l STRING")
right = spark.createDataFrame([(1, "x"), (None, "y"), (None, "z")], "k INT, r STRING")

print("inner, ==          :", left.join(right, left.k == right.k).count())
print("left, ==           :", left.join(right, left.k == right.k, "left").count())
print("left_anti, ==      :", left.join(right, left.k == right.k, "left_anti").count())
print("inner, eqNullSafe  :", left.join(right, left.k.eqNullSafe(right.k)).count())

pay = spark.createDataFrame([(1, 10.0), (1, None), (2, None)], "order_id INT, amount DOUBLE")
summary = pay.groupBy("order_id").agg(
    F.count("*").alias("rows"),
    F.count("amount").alias("amounts"),
    F.sum("amount").alias("total"),
    F.avg("amount").alias("avg"),
)
for r in summary.orderBy("order_id").collect():
    print(r["order_id"], r["rows"], r["amounts"], r["total"], r["avg"])

Run it, then check each line against the table below.

Left keys 1, 2, null against right keys 1, null, null

JoinRowsWhy
inner, ==1only 1 = 1; null = null is null, not true
left, ==3every left row once; 2 and null find nothing
leftanti, ==2the 2 and the null have no match
inner, eqNullSafe31 with 1, and the left null with each of the two right nulls

And in the aggregate: order 2 has one row whose amount is null, so count(*) is 1, count("amount") is 0, and both sum and avg are null. Wrap a sum in F.coalesce(..., F.lit(0)) when a report needs 0.

Every null lands in one task

Nulls also decide speed. To send a row to its task in a shuffle, Spark hashes the key with a function called Murmur3 and takes the remainder by the number of partitions. The hash of a null is the function's starting value, its seed: 42. With 200 shuffle partitions, pmod(42, 200) sends every null key of an outer join to partition 42.

So if one row in ten has no customer, one task gets all of them, while the other tasks finish and wait. Nulls can never match, so the fix is cheap: split them off before the join, join the rest, and union them back afterwards.

A left join where 10% of the keys are null

Bars compare a typical shuffle partition of 2.7 GB with partition 42, which also receives all 60 GB of null keys and holds 62.7 GB.

600 GB of orders left-joined on customer_id, 10% of them with no customer. The 540 GB of real keys spread evenly; every null hashes to 42. One task does 23 times the work of the others while 199 cores wait. AQE can also split the partition (Lesson 12.10).

Under the hood: the plan Spark picks

At SwiftKart's real size, revenue per country is two joins and a group-by. Spark decides how to run each join, and your code stays the same:

  • If one side is small, under spark.sql.autoBroadcastJoinThreshold (10 MB by default), Spark copies it to every executor: a broadcast join. The two columns of customers qualify.
  • If both sides are big, it shuffles both by the key and merges them: a sort-merge join. Adaptive query execution (AQE, on by default since Spark 3.2) can still switch to a broadcast once it sees the real sizes.

Read the plan below from the bottom up. Lesson 12.4 shows how the choice is made and what it costs.

Revenue per country at SwiftKart scale, as Spark plans it

A physical plan tree: a final hash aggregate over an exchange by country, a partial aggregate, a broadcast hash join with customers, and a sort-merge join of order lines and orders, each side shuffled by order_id.

Read it bottom up. The customers side is broadcast; the two big tables are both shuffled by order_id (the sorts under the join are left out). After the joins only partial sums cross the network: 200 tasks times at most 25 countries is at most 5,000 rows. The optimiser added the IsNotNull filters, because a null key can never satisfy an inner join.

Numbers to remember

Setting or ruleDefault or valueWhat to know
spark.sql.shuffle.partitions200How many tasks finish a shuffle, as in hashpartitioning(country, 200).
spark.sql.autoBroadcastJoinThreshold10 MBA side estimated under this is copied to every executor.
AQEon by default since Spark 3.2Can switch a sort-merge join to a broadcast once it sees the real sizes.
Murmur3 hash of a null key42, the seedEvery null of an outer join lands in partition pmod(42, n).
A hash map out of memoryspillSpark sorts and spills what it has, then finishes with a sort-based aggregate.
countDistinctone extra aggregation stepThe plan aggregates on (group, value) first, so the shuffle carries every distinct pair.
F.sum of only nullsnullWrap it in F.coalesce(..., F.lit(0)) when a report needs 0.

What changed at SwiftKart

The report now groups payments to one row per order and method before the join. Cards come to $2,735.51, the same as the order lines, and Tess signs it off. Order 1033's second capture is real money taken from a customer, so it goes to Dana as an app bug and a refund to make, not into revenue.

Two habits stay in every job: an alias on every aggregate, and a row count before and after every join.

Next, Lesson 11.3: the daily order files send an order again each time its status changes, and Tess's status board counts every copy.

In one line

Group with groupBy().agg() and an alias on every result, join with the right key and type, and count rows before and after every join, because a key that repeats multiplies rows.

Interview corner

How do you find rows in one DataFrame that have no match in another?

Use a.join(b, "key", "left_anti"): it keeps the rows of a with no matching key in b and returns only a's columns. A left join plus a null filter on a right-side column works too, but the anti join states the intent and cannot repeat rows. The opposite, rows that do have a match, is left_semi.

Your join returns more rows than the left table. What happened, and how do you fix it?

The key is not unique on the right side, so each left row is repeated once per match: a fan-out. Check with groupBy(key).count().filter("count > 1") on the right side. Fix it by aggregating or deduplicating the right side to one row per key before the join, and add a uniqueness check to the pipeline.

How does Spark run `groupBy("country").agg(F.sum("amount"))` on a billion rows?

In two aggregation steps around one shuffle. Each map task builds a hash map from country to a partial sum over its own rows, so it emits at most one row per country; those rows are shuffled by hashpartitioning(country, 200) (the default spark.sql.shuffle.partitions), and each reduce task merges the partial sums for its keys. The shuffle therefore carries tasks times groups rows, not a billion. If a hash map cannot get memory, Spark spills sorted runs and falls back to a sort-based aggregate; countDistinct adds an extra aggregation level and shuffles the distinct pairs.

One task of a left join runs for an hour while 199 finish in a minute. How do you diagnose and fix it?

Open the stage in the Spark UI and compare the task metrics: one task with a huge shuffle read is data skew, not a slow machine. Count the join key's values, nulls included: null keys all hash to Murmur3's seed (42), so with 200 partitions every null of an outer join lands in partition 42. Split the null-key rows off, join the rest and union them back; for hot non-null keys, salt the key or let AQE's skew join split the partition (spark.sql.adaptive.skewJoin.enabled, on by default).