Aggregations and joins
Spark / PySpark · 13 questions
Short notes
Key idea
Aggregations summarise rows per group; joins combine DataFrames on keys. Both usually shuffle, so their cost depends on how much data moves.
Syntax
from pyspark.sql import functions as F
df.groupBy("city").agg(F.count("*").alias("orders"),
F.sum("amount").alias("revenue"),
F.countDistinct("customer_id").alias("customers"))
orders.join(customers, on="customer_id", how="left")
orders.join(customers, orders.cust == customers.id, "inner")
how: inner, left, right, full, left_semi (keep matches, no columns added), left_anti (keep non-matches).
Example
Customers who never ordered: customers.join(orders, "customer_id", "left_anti"). One line, and no NULL checks needed.
Traps
- Duplicate keys multiply rows, as in SQL and pandas.
- Joining on an expression with the same column name on both sides gives two columns with one name; join with
on="col"or rename. - NULL keys never match.
countDistincton huge data is costly;approx_count_distinctis much cheaper when an estimate will do.
Want the full lesson with step-by-step examples, a project and a certificate? Spark / PySpark course, ₹120 →
- Question 1easy
Which join returns customers who have no orders?
- Question 2medium
What does
customers.join(orders, "customer_id", "left_semi")return? - Question 3medium
What does this print?
a = spark.createDataFrame([(1, "x"), (2, "y")], ["k", "a"]) b = spark.createDataFrame([(1, "p"), (1, "q"), (1, "r"), (3, "s")], ["k", "b"]) print(a.join(b, "k", "left").count())
- Question 4medium
After
orders.join(customers, orders.customer_id == customers.customer_id), selecting "customer_id" fails. Why? - Question 5hard
You inner-join orders to customers on customer_id. 500 orders have a NULL customer_id. What happens to them?
Aggregations and joins
Aggregations and joins
Aggregations and joins
Aggregations and joins
Aggregations and joins
8 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.