正如@Oli 提到的聚合函数可以在窗口(第一种情况)以及分组(第二种情况)中使用。在性能方面,“带分组的聚合函数”比“带窗口的聚合函数”要快得多。我们可以通过分析物理计划来可视化这一点。
df.groupBy("id").agg(sum($"expense").alias("total_expense")).explain()
df.show
+---+----------+
| id| expense|
+---+----------+
| 1| 100|
| 2| 300|
| 1| 100|
| 3| 200|
+---+----------+
1- 与窗口聚合:
df.withColumn("total_expense", sum(col("expense")) over window).show
+---+----------+-------------------+
| id| expense| total_expense|
+---+----------+-------------------+
| 3| 200| 200|
| 1| 100| 200|
| 1| 100| 200|
| 2| 300| 300|
+---+----------+-------------------+
df.withColumn("total_expense", sum(col("expense")) over window).explain
== Physical Plan ==
Window [sum(cast(expense#9 as bigint)) windowspecdefinition(id#8, specifiedwindowframe(RowFrame, unboundedpreceding$(), unboundedfollowing$())) AS total_expense#265L], [id#8]
+- *(2) Sort [id#8 ASC NULLS FIRST], false, 0
+- Exchange hashpartitioning(id#8, 200), true, [id=#144]
+- *(1) Project [_1#3 AS id#8, _2#4 AS expense#9]
+- *(1) SerializeFromObject [staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString, knownnotnull(assertnotnull(input[0, scala.Tuple2, true]))._1, true, false) AS _1#3, knownnotnull(assertnotnull(input[0, scala.Tuple2, true]))._2 AS _2#4]
+- Scan[obj#2]
2- 使用 GroupBy 进行聚合:
df.groupBy("id").agg(sum($"expense").alias("total_expense")).show
+---+------------------+
| id| total_expense|
+---+------------------+
| 3| 200|
| 1| 200|
| 2| 300|
+---+------------------+
df.groupBy("id").agg(sum($"expense").alias("total_expense")).explain()
== Physical Plan ==
*(2) HashAggregate(keys=[id#8], functions=[sum(cast(expense#9 as bigint))])
+- Exchange hashpartitioning(id#8, 200), true, [id=#44]
+- *(1) HashAggregate(keys=[id#8], functions=[partial_sum(cast(expense#9 as bigint))])
+- *(1) Project [_1#3 AS id#8, _2#4 AS expense#9]
+- *(1) SerializeFromObject [staticinvoke(class org.apache.spark.unsafe.types.UTF8String, StringType, fromString, knownnotnull(assertnotnull(input[0, scala.Tuple2, true]))._1, true, false) AS _1#3, knownnotnull(assertnotnull(input[0, scala.Tuple2, true]))._2 AS _2#4]
+- Scan[obj#2]
根据执行计划,我们可以看到在 windows 的情况下,有一个总 shuffle 和一个 sort,而在 groupby 的情况下,有一个 reduced shuffle(在本地聚合 partial_sum 之后的shuffle)。