如何在Spark Streaming中将DStream [(Array [String],Long)]转换为数据帧

时间:2019-02-09 20:10:24

标签: spark-streaming

我正在尝试将dstream转换为Dataframe。以下是用于将dstream转换为Dataframe的代码

           val ssc = new StreamingContext(spark.sparkContext, Seconds(10))
           val kafkaParams = Map[String, Object](
           "bootstrap.servers" -> "ffff.dl.uk.fff.com:8002",
           "security.protocol" -> "SASL_PLAINTEXT",
           "key.deserializer" -> classOf[StringDeserializer],
           "value.deserializer" -> classOf[StringDeserializer],
           "group.id" -> "1",
           "auto.offset.reset" -> "latest",
           "enable.auto.commit" -> (false: java.lang.Boolean)
           )

           val topics = Array("mytopic")
           val from_kafkastream = KafkaUtils.createDirectStream[String, 
           String](
           ssc,
           PreferConsistent,
           Subscribe[String, String](topics, kafkaParams)
           )
           val strmk = from_kafkastream.map(record => 
          (record.value,record.timestamp))
          val splitup2 = strmk.map{ case (line1, line2) => 
   (line1.split(","),line2)}

          case class Record(name: String, trQ: String, traW: String,traNS: 
   String, traned: String, tranS: String,transwer: String, trABN: 
  String,kafkatime: Long)

          object SQLContextSingleton {
            @transient  private var instance: SQLContext = _

            def getInstance(sparkContext: SparkContext): SQLContext = {
              if (instance == null) {
                instance = new SQLContext(sparkContext)
              }
              instance
            }
          }
          splitup2.foreachRDD((rdd) => {
          val sqlContext = SQLContextSingleton.getInstance(rdd.sparkContext)
          spark.sparkContext.setLogLevel("ERROR")
          import sqlContext.implicits._
          val requestsDataFrame = rdd.map(w => Record(w(0).toString, 
  w(1).toString, w(2).toString,w(3).toString, w(4).toString, 
  w(5).toString,w(6).toString, w(7).toString,w(8).toString)).toDF()
          // am getting issue here
          requestsDataFrame.show()
          })
          ssc.start()

我在跟随enter image description here

时说错了

当我是新火花世界时,有人可以帮助我如何将dstream转换为DF

1 个答案:

答案 0 :(得分:3)

也许错误是在构建Record对象时,因为您没有传递kafkatime,仅传递了字符串值,并且是元组,您无法访问此形式的属性数组。

您可以尝试以下方法:

import session.sqlContext.implicits._
val requestsDataFrame = rdd.map(w => Record(
  w._1(0).toString,
  w._1(1).toString, w._1(2).toString, w._1(3).toString, w._1.toString,
  w._1(5).toString, w._1(6).toString, w._1(7).toString, w._2))

requestsDataFrame.toDF()