查找每小时的广告点击次数

Find number of ad clicks in each hour

我对火花和学习 it.I 运行 很陌生,我想在墙上找到每小时的点击次数。鉴于此 table: adclicks_schema

到目前为止,我是这样转换时间戳的:

timestamp_only = adclicks.selectExpr(["to_timestamp(timestamp) as timestamp"])

click_count_by_hour = adclicks.select("timestamp")

click_count_by_hours.show(24)

我卡住了,接下来我该做什么?有没有我可以使用的 spark sql 函数?

您可以在内置函数中使用 小时(或)date_format 从时间戳中提取 hour

  • groupBy 在 hourcount 条记录上。

Example:

#sample data
df.show()
#+-------------------+
#|          timestamp|
#+-------------------+
#|2019-10-01 12:22:34|
#|2019-10-01 13:22:34|
#+-------------------+

from pyspark.sql.functions import *

df.withColumn("hour",hour(col("timestamp"))).\
groupBy("hour").\
agg(count("*").alias("count")).\
show()
#+----+-----+
#|hour|count|
#+----+-----+
#|  12|    1|
#|  13|    1|
#+----+-----+

#using date_format function

df.withColumn("hour",date_format(col("timestamp").cast("timestamp"),"yyyy-MM-dd HH")).\
groupBy("hour").\
agg(count("*").alias("count")).\
show()
#+-------------+-----+
#|         hour|count|
#+-------------+-----+
#|2019-10-01 13|    1|
#|2019-10-01 12|    1|
#+-------------+-----+