Sub topic 3
Grouping and Aggregating
Assume you know basic Python or SQL, understand rows and columns, and can run a Databricks notebook attached to compute. This chapter uses an existing orders DataFrame.
Grouping and aggregating
groupBy collects rows with the same key. An aggregation calculates one result for each group. For example, this summarizes orders by customer:
from pyspark.sql import functions as F
summary = (
orders
.groupBy("customer")
.agg(
F.count("*").alias("order_count"),
F.sum("amount").alias("total_amount"),
F.avg("amount").alias("average_amount"),
)
.orderBy(F.col("total_amount").desc())
)
display(summary)count("*") counts every row. sum and avg ignore null amounts. Aggregation reduces several input rows to one output row per customer.
Joining DataFrames
A join combines columns from two DataFrames using matching keys. A left join keeps every row from the left DataFrame, even when there is no match:
enriched = orders.join(customers, on="customer", how="left")
display(enriched)Check the key columns before joining. Duplicate keys on either side can multiply rows.
Window functions
A window function calculates across related rows without collapsing them. This running total keeps every order:
from pyspark.sql import Window
window = Window.partitionBy("customer").orderBy("order_date")
running = orders.withColumn(
"running_total",
F.sum("amount").over(window),
)
display(running)Add a unique tie-breaker to the ordering when several rows have the same date.
Mixing SQL and DataFrames
A temporary view exposes a DataFrame to SQL in the current Spark session:
orders.createOrReplaceTempView("orders_v")
top_customers = spark.sql("""
SELECT customer, SUM(amount) AS total_amount
FROM orders_v
GROUP BY customer
ORDER BY total_amount DESC
""")
display(top_customers)The SQL result is a DataFrame, so you can continue using DataFrame methods.
Saving results as tables
Use saveAsTable when another notebook or job should read the result:
summary.write.mode("overwrite").saveAsTable(
"main.default.customer_summary"
)Use append only when adding rows is intentional. Confirm the catalog and schema before writing.
Plans, shuffles, and caching
explain() shows scans, joins, and exchanges. An exchange usually means a shuffle, where Spark moves data between workers. Grouping and joins often require shuffles.
joined = orders.join(customers, "customer", "left")
joined.explain()
joined.cache()
joined.count()Caching can help when you reuse the same result. It can waste memory when used for a single action.
UDFs and pandas conversion
Prefer built-in functions such as F.round, F.when, and F.to_date. They allow Spark to optimize execution. A Python UDF is appropriate only when the logic cannot be expressed with built-in functions. UDFs often add serialization overhead.
toPandas() collects data on the driver and can exhaust its memory. Filter and aggregate first, then convert only a small result:
small_result = summary.limit(1000).toPandas()Exercise
Why might a join or groupBy make a Spark job slow, and when can caching help?
Show answer
They can cause a shuffle that moves data between workers. Caching can help when the same computed result is used by multiple later actions.