有没有办法将groupby的结果流连接回kafka spark结构化流中的原始流?

thtygnil  于 2021-06-06  发布在  Kafka
关注(0)|答案(1)|浏览(247)

我在读Kafka主题中的一条小溪。我正在对事件时间执行窗口groupby操作。现在,我想把groupby的结果流加入到原始流中。


# I am reading from a Kafka topic. The following is a ping statement:

2019-04-15 13:32:33 | 64 bytes from google.com (X.X.X.X): icmp_seq=476 ttl=63 time=0.201ms
2019-04-15 13:32:34 | 64 bytes from google.com (X.X.X.X): icmp_seq=477 ttl=63 time=0.216ms
2019-04-15 13:32:35 | 64 bytes from google.com (X.X.X.X): icmp_seq=478 ttl=63 time=0.245ms
2019-04-15 13:32:36 | 64 bytes from google.com (X.X.X.X): icmp_seq=479 ttl=63 time=0.202ms
and so on..

root
|--key: binary
|--value: binary
|--topic: string
|--partition: integer
|--offset:long
|--timestamp:timestamp
|--timestampType:integer

# value contains the above ping statement so, I cast it as string.

words = lines.selectExpr("CAST(value AS STRING)")

# Now I split that line into columns with its values.

words = words.withColumn('string_val', F.regexp_replace(F.split(words.value, " ")[6], ":", "")) \
.withColumn('ping', F.regexp_replace(F.split(words.value, " ")[10], "time=", "").cast("double")) \
.withColumn('date', F.split(words.value, " ")[0]) \
.withColumn('time', F.regexp_replace(F.split(words.value, " ")[1], "|", ""))

words = words.withColumn('date_time', F.concat(F.col('date'), F.lit(" "), F.col('time')))
words = words.withColumn('date_format', F.col('date_time').cast('timestamp'))

# Now the schema becomes like this

root
|--value:string
|--string_val:string
|--ping:double
|--date:string
|--time:string
|--date_time:string
|--date_format:timestamp

# Now I have to perform a windowed groupBy operation with watermark

w = F.window('date_format', '30 seconds', '10 seconds')
words = words \
.withWatermark('date_format', '1 minutes') \
.groupBy(w).agg(F.mean('ping').alias('value'))

# Now my schema becomes like this

root
|--window:struct
|   |--start:timestamp
|   |--end:timestamp
|--value

有没有办法将这个结果流连接回它的原始流?

5us2dqdw

5us2dqdw1#

使用spark 2.3中引入的“流到流连接”可以实现这一点。对于spark 2.3之前的任何版本,您必须将聚合持久化到某个存储区(内存或磁盘)中,并将原始流与用于存储聚合状态的此存储区执行左外连接。

相关问题