Spark 中的循环分区是如何工作的?

Rap*_*oth 5 scala partitioning apache-spark

我很难理解 Spark 中的循环分区。考虑以下示例。我将大小为 3 的 Seq 拆分为 3 个分区:

val df = Seq(0,1,2).toDF().repartition(3)

df.explain

== Physical Plan ==
Exchange RoundRobinPartitioning(3)
+- LocalTableScan [value#42]
Run Code Online (Sandbox Code Playgroud)

现在,如果我检查分区,我会得到:

df
  .rdd
  .mapPartitionsWithIndex{case (i,rows) => Iterator((i,rows.size))}
  .toDF("partition_index","number_of_records")
  .show

+---------------+-----------------+
|partition_index|number_of_records|
+---------------+-----------------+
|              0|                0|
|              1|                2|
|              2|                1|
+---------------+-----------------+
Run Code Online (Sandbox Code Playgroud)

如果我对大小为 8 的 Seq 执行相同操作并将其拆分为 8 个分区,则会出现更严重的偏差:

(0 to 7).toDF().repartition(8)
  .rdd
  .mapPartitionsWithIndex{case (i,rows) => Iterator((i,rows.size))}
  .toDF("partition_index","number_of_records")
  .show

+---------------+-----------------+
|partition_index|number_of_records|
+---------------+-----------------+
|              0|                0|
|              1|                0|
|              2|                0|
|              3|                0|
|              4|                0|
|              5|                0|
|              6|                4|
|              7|                4|
+---------------+-----------------+
Run Code Online (Sandbox Code Playgroud)

有人可以解释这种行为。据我了解循环分区,所有分区都显示为相同大小。

Ser*_*kov 4

(检查 Spark 版本 2.1-2.4)

据我从ShuffleExchangeExec代码中可以看到,Spark 尝试直接从原始分区(通过)对行进行分区,mapPartitions而不向驱动程序带来任何内容。

逻辑是从随机选择的目标分区开始,然后以循环方法将分区分配给行。请注意,为每个源分区选择“起始”分区,并且可能会发生冲突。

最终的分布取决于许多因素:源/目标分区的数量以及数据框中的行数。