繁体   English   中英

如何使用 (Py)Spark Structured Streaming 定义带有时间戳的 JSON 记录的架构(来自 Kafka)? - 显示 null 值

[英]How to define schema for JSON records with timestamp (from Kafka) using (Py)Spark Structured Streaming? - null values shown

问题是在使用 PySpark 读取 Kafka 消息后,我得到了null值。

我使用 Spark 2.3.1 / Scala 2.11.12

我的代码:

allData = spark \
  .readStream \
  .format("kafka") \
  .option("kafka.bootstrap.servers", "localhost:9092") \
  .option("subscribe", "mysql.login") \
  .option("startingOffsets", "earliest") \
  .load()

df = allData.selectExpr("cast(value as string)", "timestamp", "topic" )

detailSchema = StructType() \
    .add("username", StringType()) \
    .add("login_time", DateType())

df2 = df.select(from_json(col('value'), detailSchema).alias('data'), 'timestamp', 'topic')

writeStream3 = df2 \
    .writeStream \
    .trigger(processingTime= '4 seconds') \
    .format('console') \
    .outputMode('update') \
    .start()

writeStream3.awaitTermination()    

使用kafka-console-consumer.sh读取的消息如下:

$ kafka-console-consumer.sh \
    --bootstrap-server 127.0.0.1:9092 \
    --topic mysql.login \
    --from-beginning
{"username":"hello kitty","login_time":1572866627000}
{"username":"chitara","login_time":1572867234000}
{"username":"hello kitty","login_time":1572868094000}

但是,当我尝试阅读消息时,我看不到值。 它在以下行之后显示为null

df2 = df.select(from_json(col('value'), detailSchema).alias('data'), 'timestamp', 'topic')

我的代码中的 output 是:

+--------------------+--------------------+-----------+
|               value|           timestamp|      topic|
+--------------------+--------------------+-----------+
|{"username":"hell...|2019-11-12 13:55:...|mysql.login|
|{"username":"chit...|2019-11-12 13:55:...|mysql.login|
|{"username":"hell...|2019-11-12 13:55:...|mysql.login|
|{"username":"leon...|2019-11-12 13:55:...|mysql.login|
|{"username":"chit...|2019-11-12 13:55:...|mysql.login|
...

+----+--------------------+-----------+
|data|           timestamp|      topic|
+----+--------------------+-----------+
|null|2019-11-12 13:55:...|mysql.login|
|null|2019-11-12 13:55:...|mysql.login|
|null|2019-11-12 13:55:...|mysql.login|
|null|2019-11-12 13:55:...|mysql.login|
|null|2019-11-12 13:55:...|mysql.login|
...

+--------+-----+
|username|count|
+--------+-----+
|    null|  242|
+--------+-----+

我认为这个问题与解析有关,这就是为什么我在from_json function 之后看到null值的原因。 为什么? 如何解决?

tl;dr使用TimestampType作为login_time


由于login_time是一个时间戳,您应该使用适当的类型,例如TimestampTypeLongType

官方文档

在不可解析字符串的情况下返回null

这正是您从from_json得到的,因为模式与输入行不匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM