GroupBy and aggregations in Apache Spark - Time & Space Complexity
When we group data and calculate summaries, the time it takes depends on how much data we have.
We want to know how the work grows as the data gets bigger.
Analyze the time complexity of the following code snippet.
from pyspark.sql import SparkSession
from pyspark.sql.functions import avg
spark = SparkSession.builder.getOrCreate()
df = spark.read.csv('data.csv', header=True, inferSchema=True)
result = df.groupBy('category').agg(avg('value').alias('average_value'))
result.show()
This code groups rows by the 'category' column and calculates the average of 'value' for each group.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning all rows to assign them to groups and then computing averages per group.
- How many times: Each row is processed once during grouping; then each group is processed once for aggregation.
As the number of rows grows, the time to group and aggregate grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations to assign groups + a few for averages |
| 100 | About 100 operations to assign groups + a few for averages |
| 1000 | About 1000 operations to assign groups + a few for averages |
Pattern observation: The work grows roughly linearly with the number of rows.
Time Complexity: O(n)
This means the time to group and aggregate grows in a straight line as the data size grows.
[X] Wrong: "Grouping always takes constant time no matter how big the data is."
[OK] Correct: Grouping must look at each row to decide its group, so more data means more work.
Understanding how grouping and aggregation scale helps you explain data processing steps clearly and confidently.
"What if we added a second grouping column? How would the time complexity change?"
Practice
groupBy function do in Apache Spark?Solution
Step 1: Understand the purpose of groupBy
ThegroupByfunction is used to split data into groups based on one or more column values.Step 2: Compare with other functions
Sorting, filtering, and joining are different operations and do not split data into groups.Final Answer:
It splits the data into groups based on column values. -> Option AQuick Check:
groupBy = splits data into groups [OK]
- Confusing groupBy with filter or sort
- Thinking groupBy changes row order
- Assuming groupBy merges DataFrames
sales after grouping by region in Spark DataFrame df?Solution
Step 1: Identify correct aggregation syntax
To calculate average after grouping, usegroupByfollowed byagg(avg(column)).Step 2: Check each option
df.groupBy("region").agg(avg("sales")) usesagg(avg("sales"))correctly. df.groupBy("region").sum("sales") uses sum, not average. df.groupBy("region").filter(avg("sales")) uses filter incorrectly. df.groupBy("region").select(avg("sales")) uses select which is not valid after groupBy for aggregation.Final Answer:
df.groupBy("region").agg(avg("sales")) -> Option BQuick Check:
groupBy + agg(avg) = df.groupBy("region").agg(avg("sales")) [OK]
- Using sum instead of avg for average
- Using filter instead of agg
- Using select after groupBy without agg
from pyspark.sql import SparkSession
from pyspark.sql.functions import sum
spark = SparkSession.builder.getOrCreate()
data = [("East", 100), ("West", 200), ("East", 150)]
df = spark.createDataFrame(data, ["region", "sales"])
result = df.groupBy("region").agg(sum("sales").alias("total_sales"))
result.show()Solution
Step 1: Understand groupBy and sum aggregation
The code groups rows by "region" and sums the "sales" values for each group.Step 2: Calculate sums for each region
For "East": 100 + 150 = 250; For "West": 200.Final Answer:
region | total_sales East | 250 West | 200 -> Option AQuick Check:
Sum sales by region = 250 (East), 200 (West) [OK]
- Not summing all values per group
- Confusing alias name with original column
- Expecting original rows without aggregation
df.groupBy("category").agg(sum("amount"), avg("amount"))Solution
Step 1: Check function imports
The code usessumandavgfunctions but does not show imports frompyspark.sql.functions.Step 2: Validate other options
agg() accepts multiple arguments; aliasing is optional; groupBy works with agg.Final Answer:
sum and avg functions are not imported. -> Option DQuick Check:
Missing imports cause NameError [OK]
- Assuming agg needs dict, but it accepts multiple args
- Forgetting to import sum, avg from pyspark.sql.functions
- Thinking groupBy can't be chained with agg
sales_df with columns store, product, and revenue. You want to find the maximum revenue per store and the average revenue per product across all stores in a single query. Which code snippet correctly achieves this?Solution
Step 1: Understand the requirements
We need max revenue per store and average revenue per product in one result.Step 2: Analyze options
sales_df.groupBy("store").agg(max("revenue").alias("max_revenue"), avg("revenue").alias("avg_revenue")) aggregates both by store only, so avg revenue per product is incorrect. sales_df.agg(max("revenue").alias("max_revenue"), avg("revenue").alias("avg_revenue")) aggregates globally, losing grouping. sales_df.groupBy("store").agg(max("revenue").alias("max_revenue")).groupBy("product").agg(avg("revenue").alias("avg_revenue")) tries chaining groupBy but overwrites previous aggregation. sales_df.groupBy("store").agg(max("revenue").alias("max_revenue")).crossJoin(sales_df.groupBy("product").agg(avg("revenue").alias("avg_revenue"))) computes both groupings separately and joins results, correctly combining both summaries.Final Answer:
sales_df.groupBy("store").agg(max("revenue").alias("max_revenue")).crossJoin(sales_df.groupBy("product").agg(avg("revenue").alias("avg_revenue"))) -> Option CQuick Check:
Separate groupBy + crossJoin combines both aggregations [OK]
- Trying to aggregate different groupings in one groupBy
- Overwriting aggregation by chaining groupBy
- Forgetting to join separate aggregation results
Ready to prove it?
Pass the test and this pattern moves unknown
