我已将Kafka Stream连接到Spark。我已经根据流文本训练了Apache Spark Mlib模型进行预测。我的问题是,得到一个预测,我需要传递一个DataFramework。
//kafka stream
val stream = KafkaUtils.createDirectStream[String, String](
ssc,
PreferConsistent,
Subscribe[String, String](topics, kafkaParams)
)
//load mlib model
val model = PipelineModel.load(modelPath)
stream.foreachRDD { rdd =>
rdd.foreach { record =>
//to get a prediction need to pass DF
val toPredict = spark.createDataFrame(Seq(
(1L, record.value())
)).toDF("id", "review")
val prediction = model.transform(test)
}
}
我的问题是,Spark流不允许创建DataFrame。有没有办法做到这一点?我可以使用案例类或结构吗?
答案 0 :(得分:2)
可以像在核心Spark中一样从RDD创建DataFrame
或Dataset
。为此,我们需要应用架构。在foreachRDD
中,我们可以将生成的RDD转换为可以进一步与ML管道一起使用的DataFrame。
// we use a schema in the form of a case class
case class MyStructure(field:type, ....)
// and we implement our custom transformation from string to our structure
object MyStructure {
def parse(str: String) : Option[MyStructure] = ...
}
val stream = KafkaUtils.createDirectStream...
// give the stream a schema using a case class
val strucStream = stream.flatMap(cr => MyStructure.parse(cr.value))
strucStream.foreachRDD { rdd =>
import sparkSession.implicits._
val df = rdd.toDF()
val prediction = model.transform(df)
// do something with df
}