执行"groupBy()"时,多个 pyspark "window()"调用显示错误



这个问题是这个答案的后续。出现以下情况时,Spark 显示错误:

# Group results in 12 second windows of "foo", then by integer buckets of 2 for "bar"
fooWindow = window(col("foo"), "12 seconds"))
# A sub bucket that contains values in [0,2), [2,4), [4,6]...
barWindow = window(col("bar").cast("timestamp"), "2 seconds").cast("struct<start:bigint,end:bigint>")
results = df.groupBy(fooWindow, barWindow).count()

错误是:

"多个时间窗口表达式将导致笛卡尔乘积 的行,因此目前不支持它们。

有没有办法实现所需的行为?

我能够使用这个 SO 答案的改编提出一个解决方案。

注意:此解决方案仅在最多调用一次window时才有效,这意味着不允许多个时间窗口。在 spark github 上进行快速搜索显示<= 1窗口存在硬性限制。

通过使用 withColumn 定义每行的存储桶,我们可以直接按新列进行分组:

from pyspark.sql import functions as F
from datetime import datetime as dt, timedelta as td
start = dt.now()
second = td(seconds=1)
data = [(start, 0), (start+second, 1), (start+ (12*second), 2)]
df = spark.createDataFrame(data, ('foo', 'bar'))
# Create a new column defining the window for each bar
df = df.withColumn("barWindow", F.col("bar") - (F.col("bar") % 2))
# Keep the time window as is
fooWindow = F.window(F.col("foo"), "12 seconds").start.alias("foo")
# Use the new column created
results = df.groupBy(fooWindow, F.col("barWindow")).count().show()
# +-------------------+---------+-----+
# |                foo|barWindow|count|
# +-------------------+---------+-----+
# |2019-01-24 14:12:48|        0|    2|
# |2019-01-24 14:13:00|        2|    1|
# +-------------------+---------+-----+

相关内容

  • 没有找到相关文章

最新更新