【发布时间】:2016-12-06 22:49:33
【问题描述】:
我有一个带有日志的 json 文件:
{"a": "cat1", "b": "name", "c": "Caesar", "d": "2016-10-01"}
{"a": "cat1", "b": "legs", "c": "4", "d": "2016-10-01"}
{"a": "cat1", "b": "color", "c": "black", "d": "2016-10-01"}
{"a": "cat1", "b": "tail", "c": "20cm", "d": "2016-10-01"}
{"a": "cat2", "b": "name", "c": "Dickens", "d": "2016-10-02"}
{"a": "cat2", "b": "legs", "c": "4", "d": "2016-10-02"}
{"a": "cat2", "b": "color", "c": "red", "d": "2016-10-02"}
{"a": "cat2", "b": "tail", "c": "15cm", "d": "2016-10-02"}
{"a": "cat2", "b": "ears", "c": "5cm", "d": "2016-10-02"}
{"a": "cat1", "b": "tail", "c": "10cm", "d": "2016-10-10"}
想要的输出:
("id": "cat1", "name": "Caesar", "legs": "4", "color": "black", "tail": "10cm", "day": "2016-10-10")
("id": "cat2", "name": "Dickens", "legs": "4", "color": "red", "tail": "10cm", "ears": "5cm", "day": "2016-10-02")
我可以使用 for 循环和收集逐步完成,但我需要使用地图、平面地图、aggregatebykey 和其他 spark 魔法以正确的方式完成
case class cat_input(a: String, b:String, c:String, d: String)
case class cat_output(id: String, name: String, legs: String, color: String, tail: String, day: String, ears: String, claws: String)
object CatLog {
def main(args: Array[String]) {
val sconf = new SparkConf().setAppName("Cat log")
val sc = new SparkContext(sconf)
sc.setLogLevel("WARN")
val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlContext.implicits._
val df = sqlContext.read.json("cats1.txt").as[cat_input]
val step1 = df.rdd.groupBy(_.a)
//step1 = (String, Iterator[cat_input]) = (cat1, CompactBuffer(cat_input( "cat1", "name", "Caesar", "2016-10-01"), ... ) )
val step2 = step1.map(x => x._2)
//step2 = Iterator[cat_input]
val step3 = step2.map(y => (y.b,y.c))
//step3 = ("name", "Caesar")
val step4 = step3.map( case(x,y) => { cat_output(x) = y })
// it should return cat_output(id: "cat1", name: "Caesar", legs: "4", color: "black", tail: "10cm", day: NULL, ears: NULL, claws: NULL)
- step4 明显不行
- 如何至少返回这个 cat_output(id: "cat1", name: "Caesar", leg: "4", color: "black", tail: "10cm", day: NULL, ear: NULL, claws : 空)
- 如何检查 d 列的值并在它们之间选择最新的值,并将最新的日期放入 cat_output(date)?
【问题讨论】:
标签: json scala apache-spark