5

我正在尝试将这个 json 文件读入一个配置单元表,顶级键即 1,2..,这里不一致。

{
    "1":"{\"time\":1421169633384,\"reading1\":130.875969,\"reading2\":227.138275}",
    "2":"{\"time\":1421169646476,\"reading1\":131.240628,\"reading2\":226.810211}",
    "position": 0
}

我只需要蜂巢表中的时间和读数 1,2,因为列会忽略位置。我还可以组合使用 hive 查询和 spark map-reduce 代码。感谢您的帮助。

更新,这是我正在尝试的

val hqlContext = new HiveContext(sc)

val rdd = sc.textFile(data_loc)

val json_rdd = hqlContext.jsonRDD(rdd)
json_rdd.registerTempTable("table123")
println(json_rdd.printSchema())
hqlContext.sql("SELECT json_val from table123 lateral view explode_map( json_map(*, 'int,string')) x as json_key, json_val ").foreach(println)

它抛出以下错误:

Exception in thread "main" org.apache.spark.sql.hive.HiveQl$ParseException: Failed to parse: SELECT json_val from temp_hum_table lateral view explode_map( json_map(*, 'int,string')) x as json_key, json_val
    at org.apache.spark.sql.hive.HiveQl$.createPlan(HiveQl.scala:239)
    at org.apache.spark.sql.hive.ExtendedHiveQlParser$$anonfun$hiveQl$1.apply(ExtendedHiveQlParser.scala:50)
    at org.apache.spark.sql.hive.ExtendedHiveQlParser$$anonfun$hiveQl$1.apply(ExtendedHiveQlParser.scala:49)
    at scala.util.parsing.combinator.Parsers$Success.map(Parsers.scala:136)
    at scala.util.parsing.combinator.Parsers$Success.map(Parsers.scala:135)
    at scala.util.parsing.combinator.Parsers$Parser$$anonfun$map$1.apply(Parsers.scala:242)
    at scala.util.parsing.combinator.Parsers$Parser$$anonfun$map$1.apply(Parsers.scala:242)
    at scala.util.parsing.combinator.Parsers$$anon$3.apply(Parsers.scala:222)
4

1 回答 1

4

如果您将“1”和“2”(键名)重命名为“x1”和“x2”(在 json 文件或 rdd 中),这将起作用:

val resultrdd = sqlContext.sql("SELECT x1.time, x1.reading1, x1.reading1, x2.time, x2.reading1, x2.reading2 from table123  ")
resultrdd.flatMap(row => (Array( (row(0),row(1),row(2)), (row(3),row(4),row(5)) )))

这将为您提供一个包含时间、reading1 和 reading2 的元组的 RDD。如果需要 SchemaRDD,可以将其映射到 flatMap 转换中的案例类,如下所示:

case class Record(time: Long, reading1: Double, reading2: Double)
resultrdd.flatMap(row => (Array( Record(row.getLong(0),row.getDouble(1),row.getDouble(2)), 
        Record(row.getLong(3),row.getDouble(4),row.getDouble(5))  )))
val schrdd = sqlContext.createSchemaRDD(resultrdd)

更新:

在许多嵌套键的情况下,您可以像这样解析行:

val allrdd = sqlContext.sql("SELECT * from table123")
allrdd.flatMap(row=>{
    var recs = Array[Record](); 
    for(col <- (0 to row.length-1)) { 
        row(col) match { 
            case r:Row => recs = recs :+ Record(r.getLong(2),r.getDouble(0),r.getDouble(1)); 
            case _ => ; 
        } 
    }; 
    recs 
})
于 2015-01-19T22:29:32.230 回答