Spark 2.0 版 Streaming:如何动态推断 JSON String rdd 的模式并将其转换为 DF

Spark version 2.0 Streaming : how to dynamically infer the schema of a JSON String rdd and convert it to a DF

对于 2.0 之前的版本,我可以使用 SQLContext 来执行相同的操作:

val sqlContext = new SQLContext(sc)
val stream = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](
                  ssc, kafkaParams, Set("myTopicName"))

stream.foreachRDD(
  rdd => {
     val dataFrame = sqlContext.read.json(rdd.map(_._2)) //converts json to DF
     //do your operations on this DF. You won't even require a model class.
        })

但对于最新版本,SQLContext 似乎已被弃用。那么,如何在不指定模式的情况下从 JSON 字符串 RDD 创建 DF?我可以找到使用带有 case classStructType 对象的模式进行转换的示例,但是我可以看到动态创建 DF 的唯一选项是使用 SparkSession 使用隐式反射,它不' 似乎也很好用。 Schemaless JSON String to DataFrame 的支持被Spark团队拿掉了吗?

谢谢!

with latest versions, SQLContext seems to be deprecated.

你可以用 SQLContext 做的所有事情都可以用 SparkSession 做,所以只用它作为替代品。

val spark = SparkSession.builder.getOrCreate()
import spark.implicits._

stream.foreachRDD(
  rdd => {
     val dataFrame = spark.read.json(rdd.map(_._2).toDS) 
  })