从一个在Spark 2.31(HDP 3.0)上使用窗口聚合的简单完整示例中,我可以看到Spark创建的间隔与某个整数对齐。例如,在这里我指定60秒windowDuration,Spark在最近的分钟开始第一个间隔:
>>> from pyspark.sql import functions as F
>>> df = spark.createDataFrame([("2016-03-11 09:00:07", 1),("2016-03-11 09:00:08", 1)]).toDF("date", "val")
>>> w = df.groupBy(F.window("date", "60 seconds")).agg(F.sum("val").alias("sum"))
>>> w.select(w.window.start.cast("string").alias("start"),w.window.end.cast("string").alias("end"), "sum").collect()
[Row(start='2016-03-11 09:00:00', end='2016-03-11 09:01:00', sum=2)]
是否有一种方法可以在第一条消息开始间隔,即我希望拥有以下内容:
[Row(start='2016-03-11 09:00:07', end='2016-03-11 09:01:07', sum=2)]
答案 0 :(得分:1)
您在这里=>
from pyspark.sql import functions as F
from datetime import datetime
df = spark.createDataFrame([("2016-03-11 09:00:07", 1),("2016-03-11 09:00:08", 1)]).toDF("date", "val")
startSecond = datetime.strptime(df.head()[0], '%Y-%m-%d %H:%M:%S').second
w = df.groupBy(F.window("date", "60 seconds", "60 seconds", str(startSecond) + " seconds")).agg(F.sum("val").alias("sum"))
w.select(w.window.start.cast("string").alias("start"),w.window.end.cast("string").alias("end"), "sum").collect()