繁体   English   中英

如何将 kafka 消息值转换为特定模式?

[英]How to convert kafka message value to a particular schema?

我正在尝试使用 Pyspark 从 Kafka 主题读取数据。我想将该数据转换为特定模式。 但不能这样做。

这是我尝试过的:

>> df = spark.read.format("kafka").option("kafka.bootstrap.servers", "localhost:9092").option("subscribe", "test1").load()
    
>> userSchema = StructType().add("Name", StringType(), True).add("Age", IntegerType(), True)

>> df1 = df.selectExpr("CAST(value AS STRING)")

>> df2 = df1.select(from_json(col("value"), userSchema))

>> df2.printSchema()
root
 |-- jsontostructs(value): struct (nullable = true)
 |    |-- Name: string (nullable = true)
 |    |-- Age: integer (nullable = true)

我想要的是:

>> df2.printSchema()
root
|-- Name: string (nullable = true)
|-- Age: integer (nullable = true)

有没有办法获得所需的模式?

对于面临相同问题的任何人,这是我实现此目标的方法:

 df2 = df1.select(from_json(col("value"),userSchema)).select("jsontostructs(value).*")

暂无
暂无

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

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