groupBy and agg
We continue with the cleaned clean DataFrame from lesson 2. Revenue per product from delivered orders:
delivered = clean.filter(F.col("order_status") == "DELIVERED")
(delivered
.groupBy("product_id")
.agg(F.count("*").alias("orders"),
F.sum("quantity").alias("units"),
F.round(F.avg("amount"), 2).alias("avg_amount"),
F.sum("amount").alias("revenue"))
.orderBy(F.desc("revenue"))
.show(5))+----------+------+-----+----------+----------+
|product_id|orders|units|avg_amount| revenue|
+----------+------+-----+----------+----------+
| 3| 362| 457| 6310.89|2284543.00|
| 8| 326| 417| 4475.71|1459083.00|
| 1| 319| 404| 3164.88|1009596.00|
| 6| 348| 433| 2736.11| 952167.00|
| 11| 358| 455| 2413.53| 864045.00|
+----------+------+-----+----------+----------+
only showing top 5 rowsProduct 3 (the Smartwatch) leads with ₹22.8 lakh, then product 8 (Silk Saree). agg computes several named aggregations in one pass. groupBy is a wide transformation: rows with the same key must move to the same partition (a shuffle), the most expensive thing Spark does.
Joins
customers = spark.read.csv("data/customers/", header=True, inferSchema=True)
products = spark.read.csv("data/products.csv", header=True, inferSchema=True)
city_category = (delivered
.join(customers, "customer_id") # inner join on the shared column
.join(products.select("product_id", "category"), "product_id")
.groupBy("city", "category")
.agg(F.sum("amount").alias("revenue"))
.orderBy("city", F.desc("revenue")))
city_category.show(6)+---------+-----------+---------+
| city| category| revenue|
+---------+-----------+---------+
|Bengaluru|Electronics|906941.00|
|Bengaluru| Fashion|788915.00|
|Bengaluru| Home|391845.00|
| Delhi|Electronics|915309.00|
| Delhi| Fashion|824799.00|
| Delhi| Home|460601.00|
+---------+-----------+---------+
only showing top 6 rowsJoining on a column name ("customer_id") keeps one copy of the key. For different names use orders.join(customers, orders.cust_id == customers.id) and drop the duplicate afterwards.
Every join type, with real counts
To see the differences, we add one customer with no orders and one order whose customer doesn't exist:
# One customer with no orders, and one order with an unknown customer, to see join types
extra_cust = spark.createDataFrame([(999, "New Customer", "Pune")], ["customer_id", "name", "city"])
extra_order = spark.createDataFrame([(1, 777, 4)], ["order_id", "customer_id", "quantity"])
c = customers.select("customer_id", "name", "city").unionByName(extra_cust)
o = clean.select("order_id", "customer_id", "quantity").unionByName(extra_order)
for how in ["inner", "left", "right", "full", "left_anti", "left_semi"]:
print(f"{how:<10}", o.join(c, "customer_id", how).count())inner 5315
left 5316
right 5316
full 5317
left_anti 1
left_semi 5315| Join | Rows | Keeps |
|---|---|---|
| inner | 5315 | Only orders with a known customer |
| left | 5316 | All orders (+ the unknown-customer order, with NULL name/city) |
| right | 5316 | All customers (+ the new customer, with NULL order) |
| full | 5317 | Everything from both sides |
| left_anti | 1 | Orders with NO matching customer (the bad one) |
| left_semi | 5315 | Orders that HAVE a customer, order columns only |
# Customers who never ordered (left_anti from the customer side)
c.join(o, "customer_id", "left_anti").show()+-----------+------------+----+
|customer_id| name|city|
+-----------+------------+----+
| 999|New Customer|Pune|
+-----------+------------+----+Flip the sides and left_anti answers “which customers never ordered?”: only our test customer 999.
Broadcast joins
joined = delivered.join(F.broadcast(products), "product_id")
joined.explain()== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- Project [product_id#105, order_id#103, customer_id#104, quantity#106, unit_price#107, order_status#158, order_ts#109, amount#155, order_date#156, is_big#157, name#363, category#364, price#365]
+- BroadcastHashJoin [product_id#105], [product_id#362], Inner, BuildRight, false
:- Project [order_id#103, customer_id#104, product_id#105, quantity#106, unit_price#107, status#108 AS order_status#158, order_ts#109, amount#155, order_date#156, ((amount#155 >= 5000.00) <=> true) AS is_big#157]
: +- Project [order_id#103, customer_id#104, product_id#105, quantity#106, unit_price#107, status#108, order_ts#109, (cast(quantity#106 as decimal(10,0)) * unit_price#107) AS amount#155, cast(order_ts#109 as date) AS order_date#156]
: +- Filter (((isnotnull(status#108) AND atleastnnonnulls(2, order_id#103, quantity#106)) AND (status#108 = DELIVERED)) AND isnotnull(product_id#105))
: +- FileScan csv [order_id#103,customer_id#104,product_id#105,quantity#106,unit_price#107,status#108,order_ts#109] Batched: false, DataFilters: [isnotnull(status#108), atleastnnonnulls(2, order_id#103, quantity#106), (status#108 = DELIVERED)..., Format: CSV, Location: InMemoryFileIndex(1 paths)[file:/private/tmp/claude-501/-Users-sudiptabiswas-claude/f6c71fe0-f8b1..., PartitionFilters: [], PushedFilters: [IsNotNull(status), EqualTo(status,DELIVERED), IsNotNull(product_id)], ReadSchema: struct<order_id:int,customer_id:int,product_id:int,quantity:int,unit_price:decimal(10,2),status:s...
+- BroadcastExchange HashedRelationBroadcastMode(List(cast(input[0, int, false] as bigint)),false), [plan_id=3284]
+- Filter isnotnull(product_id#362)
+- FileScan csv [product_id#362,name#363,category#364,price#365] Batched: false, DataFilters: [isnotnull(product_id#362)], Format: CSV, Location: InMemoryFileIndex(1 paths)[file:/private/tmp/claude-501/-Users-sudiptabiswas-claude/f6c71fe0-f8b1..., PartitionFilters: [], PushedFilters: [IsNotNull(product_id)], ReadSchema: struct<product_id:int,name:string,category:string,price:int>BroadcastHashJoin ... BroadcastExchange: the 12-row products table was copied to every executor, so the big orders table didn't move. Spark does this automatically for tables under 10 MB; F.broadcast() forces it. Without it, both sides are shuffled (SortMergeJoin).
🎯 Interview questions on this topic
Try to answer out loud first, then tap to check.
Q1Name the join types in PySpark.Fresher+
Q2What is a broadcast join and when do you use it?1–3 yrs+
Q3What is a shuffle?1–3 yrs+
Q4One join key has 40% of the rows and the job is slow. What do you do?3+ yrs+
Key takeaways
- ✓agg gives several named totals in one pass.
- ✓Six join types, each answering a different question: anti joins find what's missing.
- ✓Broadcast small tables; shuffles are the expensive part.
- ✓Read the plan to see which join Spark chose.
Frequently asked questions
groupBy().agg() vs groupBy().sum()?
agg lets you compute several aggregations at once with names (F.count, F.sum, F.avg, F.min, F.max, F.countDistinct). Shortcuts like .sum('x') do one thing and give ugly column names like sum(x).
What's a left anti join?
It keeps rows from the left side that have NO match on the right, with only the left's columns. Perfect for 'customers who never ordered' or 'orders with an unknown customer'.
When does Spark broadcast a table?
Automatically when one side is smaller than spark.sql.autoBroadcastJoinThreshold (10 MB by default), or when you wrap it in F.broadcast(). The small table is copied to every executor, so the big one doesn't need to be shuffled.
Why is my join creating more rows than expected?
Duplicate keys: if a key appears 3 times on the left and 2 times on the right, the join returns 6 rows for it. Check uniqueness of join keys before joining.
🧠 Quick check: groupBy and joins
1. Customers who never placed an order. Which join?
2. Our inner join returned 5,315 and full returned 5,317. Why +2?
3. BroadcastHashJoin in the plan means...
4. left_semi returns...
Checking your access…