groupBy & agg
Apache Spark · Aggregations & Joins
Theory
groupBy(cols) collects rows that share the same values in the given columns into groups, and agg(...) computes one summary row per group with aggregate functions such as F.sum, F.count, F.avg, F.min, F.max, F.countDistinct, F.collect_set and F.percentile_approx. Give every result a clear name with .alias(). Calling agg directly on a DataFrame, without groupBy, aggregates the whole table into one row.
groupBy is a wide transformation: Spark first computes partial results in each partition (partial_sum), shuffles them by the group key and then merges them, which is why it scales to billions of rows. There is no separate HAVING method: you filter the aggregated DataFrame afterwards. For example, orders.groupBy('region').agg(F.sum('amount').alias('total'), F.count('*').alias('orders')) gives North 104500 from 3 orders, and .filter('total > 50000') keeps only the big regions.
Why we use it
Totals, counts and averages per customer, region or day are the heart of reporting and feature engineering. groupBy().agg() lets you compute many metrics in a single distributed pass over the data.
When to use it
Use groupBy().agg() whenever you need one row per group. Put all metrics in one agg call instead of several groupBy jobs. Use window functions instead when you need the group total next to every original row rather than one row per group.
How it works
- DataFrame of rows
- Partial aggregation inside each partition
- Shuffle partial results by the group key
- Merge partials into one row per group
- Is there a HAVING-style condition? Yes: filter() the aggregated rows. No: Keep all groups.
- One row per group
Syntax
df.groupBy("k1", "k2").agg(F.sum("x").alias("total"), F.count("*").alias("n"))
df.groupBy("k").count()
df.agg(F.max("x")) # whole table
...agg(...).filter(F.col("total") > 100) # HAVINGExample
from pyspark.sql import SparkSession, functions as F
spark = (SparkSession.builder.master("local[1]")
.config("spark.ui.enabled", "false")
.getOrCreate())
orders = spark.createDataFrame([
(101, 1, "North", "Laptop", 1, 55000.0, "2026-01-05"),
(102, 2, "West", "Phone", 2, 30000.0, "2026-01-06"),
(103, 1, "North", "Mouse", 3, 1500.0, "2026-01-06"),
(104, 3, "South", "Laptop", 1, 52000.0, "2026-01-07"),
(105, 4, "West", "Tablet", 1, 25000.0, "2026-01-08"),
(106, 2, "East", "Phone", 1, 15000.0, "2026-01-08"),
(107, 5, "North", "Tablet", 2, 48000.0, "2026-01-09"),
(108, 3, "South", "Mouse", 4, 2000.0, "2026-01-10"),
], "order_id INT, customer_id INT, region STRING, product STRING, "
"qty INT, amount DOUBLE, order_date STRING"
).withColumn("order_date", F.to_date("order_date"))
summary = (orders.groupBy("region")
.agg(F.sum("amount").alias("total"),
F.count("*").alias("orders"),
F.round(F.avg("amount"), 1).alias("avg_amount"),
F.countDistinct("customer_id").alias("customers"),
F.sort_array(F.collect_set("product")).alias("products"))
.orderBy(F.desc("total")))
summary.show(truncate=False)
# HAVING: filter after aggregating
summary.filter(F.col("total") > 50000).select("region", "total").show()
# Whole-table aggregate (no groupBy)
orders.agg(F.sum("qty").alias("units"), F.max("amount").alias("biggest")).show()
# Output:
# +------+--------+------+----------+---------+-----------------------+
# |region|total |orders|avg_amount|customers|products |
# +------+--------+------+----------+---------+-----------------------+
# |North |104500.0|3 |34833.3 |2 |[Laptop, Mouse, Tablet]|
# |West |55000.0 |2 |27500.0 |2 |[Phone, Tablet] |
# |South |54000.0 |2 |27000.0 |1 |[Laptop, Mouse] |
# |East |15000.0 |1 |15000.0 |1 |[Phone] |
# +------+--------+------+----------+---------+-----------------------+
#
# +------+--------+
# |region| total|
# +------+--------+
# | North|104500.0|
# | West| 55000.0|
# | South| 54000.0|
# +------+--------+
#
# +-----+-------+
# |units|biggest|
# +-----+-------+
# | 15|55000.0|
# +-----+-------+
Key points
- groupBy is lazy; agg, count, sum etc. on the grouped data define the output
- Always alias aggregates; default names like sum(amount) are awkward
- Filter after agg for HAVING-style conditions
- count('*') counts rows; count('col') skips NULLs; countDistinct counts unique values
- Spark does partial aggregation before the shuffle, so groupBy scales well