避免Spark窗口函数中单个分区模式的性能影响

Yts*_*oer 15 partitioning window-functions apache-spark apache-spark-sql pyspark

我的问题是由计算spark数据帧中连续行之间差异的用例触发的.

例如,我有:

>>> df.show()
+-----+----------+
|index|      col1|
+-----+----------+
|  0.0|0.58734024|
|  1.0|0.67304325|
|  2.0|0.85154736|
|  3.0| 0.5449719|
+-----+----------+
Run Code Online (Sandbox Code Playgroud)

如果我选择使用"Window"函数计算它们,那么我可以这样做:

>>> winSpec = Window.partitionBy(df.index >= 0).orderBy(df.index.asc())
>>> import pyspark.sql.functions as f
>>> df.withColumn('diffs_col1', f.lag(df.col1, -1).over(winSpec) - df.col1).show()
+-----+----------+-----------+
|index|      col1| diffs_col1|
+-----+----------+-----------+
|  0.0|0.58734024|0.085703015|
|  1.0|0.67304325| 0.17850411|
|  2.0|0.85154736|-0.30657548|
|  3.0| 0.5449719|       null|
+-----+----------+-----------+
Run Code Online (Sandbox Code Playgroud)

问题:我在一个分区中明确地划分了数据帧.这会对性能产生什么影响,如果存在,为什么会这样,我怎么能避免它呢?因为当我没有指定分区时,我收到以下警告:

16/12/24 13:52:27 WARN WindowExec: No Partition Defined for Window operation! Moving all data to a single partition, this can cause serious performance degradation.
Run Code Online (Sandbox Code Playgroud)

use*_*411 16

在实践中,性能影响几乎与您完全忽略partitionBy条款相同.所有记录将被洗牌到一个分区,在本地排序并逐个迭代迭代.

差异仅在于总共创建的分区数.让我们举例说明使用包含10个分区和1000个记录的简单数据集的示例:

df = spark.range(0, 1000, 1, 10).toDF("index").withColumn("col1", f.randn(42))
Run Code Online (Sandbox Code Playgroud)

如果您定义没有partition by子句的框架

w_unpart = Window.orderBy(f.col("index").asc())
Run Code Online (Sandbox Code Playgroud)

并使用它 lag

df_lag_unpart = df.withColumn(
    "diffs_col1", f.lag("col1", 1).over(w_unpart) - f.col("col1")
)
Run Code Online (Sandbox Code Playgroud)

总共只有一个分区:

df_lag_unpart.rdd.glom().map(len).collect()
Run Code Online (Sandbox Code Playgroud)
[1000]
Run Code Online (Sandbox Code Playgroud)

与具有虚拟索引的帧定义相比(与您的代码相比简化了一点:

w_part = Window.partitionBy(f.lit(0)).orderBy(f.col("index").asc())
Run Code Online (Sandbox Code Playgroud)

将使用等于的分区数spark.sql.shuffle.partitions:

spark.conf.set("spark.sql.shuffle.partitions", 11)

df_lag_part = df.withColumn(
    "diffs_col1", f.lag("col1", 1).over(w_part) - f.col("col1")
)

df_lag_part.rdd.glom().count()
Run Code Online (Sandbox Code Playgroud)
11
Run Code Online (Sandbox Code Playgroud)

只有一个非空分区:

df_lag_part.rdd.glom().filter(lambda x: x).count()
Run Code Online (Sandbox Code Playgroud)
1
Run Code Online (Sandbox Code Playgroud)

遗憾的是,没有通用的解决方案可以用来解决PySpark中的这个问题.这只是实现的固有机制与分布式处理模型相结合.

由于index列是顺序的,因此您可以生成每个块具有固定数量记录的人工分区键:

rec_per_block  = df.count() // int(spark.conf.get("spark.sql.shuffle.partitions"))

df_with_block = df.withColumn(
    "block", (f.col("index") / rec_per_block).cast("int")
)
Run Code Online (Sandbox Code Playgroud)

并用它来定义框架规范:

w_with_block = Window.partitionBy("block").orderBy("index")

df_lag_with_block = df_with_block.withColumn(
    "diffs_col1", f.lag("col1", 1).over(w_with_block) - f.col("col1")
)
Run Code Online (Sandbox Code Playgroud)

这将使用预期的分区数:

df_lag_with_block.rdd.glom().count()
Run Code Online (Sandbox Code Playgroud)
11
Run Code Online (Sandbox Code Playgroud)

大致统一的数据分布(我们无法避免哈希冲突):

df_lag_with_block.rdd.glom().map(len).collect()
Run Code Online (Sandbox Code Playgroud)
[0, 180, 0, 90, 90, 0, 90, 90, 100, 90, 270]
Run Code Online (Sandbox Code Playgroud)

但是在块边界上有许多空白:

df_lag_with_block.where(f.col("diffs_col1").isNull()).count()
Run Code Online (Sandbox Code Playgroud)
12
Run Code Online (Sandbox Code Playgroud)

由于边界易于计算:

from itertools import chain

boundary_idxs = sorted(chain.from_iterable(
    # Here we depend on sequential identifiers
    # This could be generalized to any monotonically increasing
    # id by taking min and max per block
    (idx - 1, idx) for idx in 
    df_lag_with_block.groupBy("block").min("index")
        .drop("block").rdd.flatMap(lambda x: x)
        .collect()))[2:]  # The first boundary doesn't carry useful inf.
Run Code Online (Sandbox Code Playgroud)

你总是可以选择:

missing = df_with_block.where(f.col("index").isin(boundary_idxs))
Run Code Online (Sandbox Code Playgroud)

并分别填写:

# We use window without partitions here. Since number of records
# will be small this won't be a performance issue
# but will generate "Moving all data to a single partition" warning
missing_with_lag = missing.withColumn(
    "diffs_col1", f.lag("col1", 1).over(w_unpart) - f.col("col1")
).select("index", f.col("diffs_col1").alias("diffs_fill"))
Run Code Online (Sandbox Code Playgroud)

并且join:

combined = (df_lag_with_block
    .join(missing_with_lag, ["index"], "leftouter")
    .withColumn("diffs_col1", f.coalesce("diffs_col1", "diffs_fill")))
Run Code Online (Sandbox Code Playgroud)

获得理想的结果:

mismatched = combined.join(df_lag_unpart, ["index"], "outer").where(
    combined["diffs_col1"] != df_lag_unpart["diffs_col1"]
)
assert mismatched.count() == 0
Run Code Online (Sandbox Code Playgroud)

  • `partitionBy` 用于在应用函数之前对数据进行打乱。由于“lit(0)”是常量,因此所有记录都必须移动到同一分区。 (2认同)