TECHNOLOGIESTieInn Technologies

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.
  • countDistinct on huge data is costly; approx_count_distinct is 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 →

Questions

Open in Code Lab5 free questions
5 questions

    Aggregations and joins

  1. Question 1easy

    Which join returns customers who have no orders?

  2. Aggregations and joins

  3. Question 2medium

    What does customers.join(orders, "customer_id", "left_semi") return?

  4. Aggregations and joins

  5. 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())
  6. Aggregations and joins

  7. Question 4medium

    After orders.join(customers, orders.customer_id == customers.customer_id), selecting "customer_id" fails. Why?

  8. Aggregations and joins

  9. Question 5hard

    You inner-join orders to customers on customer_id. 500 orders have a NULL customer_id. What happens to them?

8 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.