繁体   English   中英

如何将RDD [(String,Any)]转换为Array(Row)?

[英]how to convert RDD[(String, Any)] to Array(Row)?

我有一个带有键和值的非结构化RDD。 值是RDD [Any],键当前是Strings,RDD [String],主要包含Maps。 我想将它们设置为Row类型,以便最终制作一个数据框。 这是我的rdd:

已移除

除了最后4个键外,大多数rdd都遵循一种模式,该如何处理? 也许将它们拆分为自己的rdd,尤其是对于reverseDeltas?

谢谢

编辑

到目前为止,根据下面的第一个答案,这就是我很累的地方。

case class MyData(`type`: List[String], libVersion: Double, id: BigInt)

object MyDataBuilder{
    def apply(s: Any): MyData = {
      // read the input data and convert that to the case class

      s match {
        case Array(x: List[String], y: Double, z: BigInt) => MyData(x, y, z)
        case Array(a: BigInt, Array(x: List[String], y: Double, z: BigInt)) => MyData(x, y, z)
        case _ => null
      }
    }
  }

val parsedRdd: RDD[MyData] = rdd.map(x => MyDataBuilder(x))

如何看不到匹配任何这些情况,如何在Scala中的Map进行匹配? 打印出parsedRdd时,我不断返回null

要将RDD转换为数据框,您需要具有固定的架构。 如果为RDD定义架构,其余的操作很简单。

就像是

val rdd2:RDD[Array[String]] = rdd.map( x => getParsedRow(x)) 
val rddFinal:RDD[Row] = rdd2.map(x => Row.fromSeq(x))

备用

case class MyData(....) // all the fields of the Schema I want
object MyDataBuilder {
  def apply(s:Any):MyData ={
    // read the input data and convert that to the case class
  }
}

val rddFinal:RDD[MyData] = rdd.map(x => MyDataBuilder(x))
import spark.implicits._
val myDF = rddFinal.toDF

有一种将rdd转换为数据帧的方法,如下所示

val rdd = sc.textFile("/pathtologfile/logfile.txt")
val df = rdd.toDF()

不,你有数据框使用下面的SQL查询做你想做的事

val textFile = sc.textFile("hdfs://...")
// Creates a DataFrame having a single column named "line"
val df = textFile.toDF("line")
val errors = df.filter(col("line").like("%ERROR%"))
// Counts all the errors
errors.count()
// Counts errors mentioning MySQL
errors.filter(col("line").like("%MySQL%")).count()
// Fetches the MySQL errors as an array of strings
errors.filter(col("line").like("%MySQL%")).collect()

暂无
暂无

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

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