QuestionQ282

VerifiedCost & Performance Optimisation

A data engineer is trying to run the following PySpark code:

df = spark.read.table("sales")  
result = df.groupBy("region").agg(sum("revenue"))  

After reviewing the execution plan and profiling the Spark job, they find excessive data shuffling during the aggregation phase.

Which technique should be used to reduce shuffling during the groupBy aggregation operation?

Explanation

A groupBy("region") aggregation needs records sharing a region value to be colocated. Repartitioning by region creates that key-based distribution before the aggregation, allowing Spark to use it to perform the aggregation without an additional redistribution for the grouping. coalesce(1) after the aggregation only changes output partitioning, caching does not establish key distribution, and broadcast join applies to join operations. Apache Spark documents that repartitioning by specified columns produces hash partitioning by those columns.

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!