Spark JSON 文本字段到 RDD

Spark JSON text field to RDD

我有一个 cassandra table,其中包含一个名为 snapshot 的文本类型字段,其中包含 JSON 个对象:

[identifier, timestamp, snapshot]

我了解到,为了能够使用 Spark 对该字段进行转换,我需要将该 RDD 的该字段转换为另一个 RDD,以便对 JSON 模式进行转换。

对吗?我应该如何进行?

编辑:现在我设法从单个文本字段创建了一个 RDD:

val conf = new SparkConf().setAppName("signal-aggregation")
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)
val snapshots = sc.cassandraTable[(String, String, String)]("listener", "snapshots")
val first = snapshots.first()
val firstJson = sqlContext.jsonRDD(sc.parallelize(Seq(first._3)))
firstJson.printSchema()

这向我展示了 JSON 架构。好!

我如何继续告诉 Spark 这个模式应该应用于 table 快照的所有行,以便从每一行的快照字段上获取 RDD?

差不多了,你只想将你的 RDD[String] 和你的 json 传递到 jsonRDD 方法

val conf = new SparkConf().setAppName("signal-aggregation")
val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)
val snapshots = sc.cassandraTable[(String, String, String)]("listener", "snapshots")
val jsons = snapshots.map(_._3) // Get Third Row Element Json(RDD[String]) 
val jsonSchemaRDD = sqlContext.jsonRDD(jsons) // Pass in RDD directly
jsonSchemaRDD.registerTempTable("testjson")
sqlContext.sql("SELECT * FROM testjson where .... ").collect 

一个简单的例子

val stringRDD = sc.parallelize(Seq(""" 
  { "isActive": false,
    "balance": ",431.73",
    "picture": "http://placehold.it/32x32",
    "age": 35,
    "eyeColor": "blue"
  }""",
   """{
    "isActive": true,
    "balance": ",515.60",
    "picture": "http://placehold.it/32x32",
    "age": 34,
    "eyeColor": "blue"
  }""", 
  """{
    "isActive": false,
    "balance": ",765.29",
    "picture": "http://placehold.it/32x32",
    "age": 26,
    "eyeColor": "blue"
  }""")
)
sqlContext.jsonRDD(stringRDD).registerTempTable("testjson")
csc.sql("SELECT age from testjson").collect
//res24: Array[org.apache.spark.sql.Row] = Array([35], [34], [26])