我有一组带有嵌套键值对的大压缩json文件。json对象中大约有70-80个键(和子键),但是,我只对几个键感兴趣。我想用Spark SQL查询json文件,只挑出我感兴趣的键值对,并将它们输出到一组csv文件。处理一个170MB的json压缩文件大约需要5分钟。我只是想知道是否有什么方法可以优化这个过程。或者除了Spark之外,还有更好的工具来完成这类工作吗?谢谢!
下面是我使用的scala代码的快照:
val data = sc.textFile("abcdefg.txt.gz")
// repartition the data
val distdata = data.repartition(10)
val dataDF = sqlContext.read.json(distdata)
// register a temp table
dataDF.registerTempTable("pixels")
// query the json file, grab columns of interest
val query =
"""
|SELECT col1, col2, col3, col4, col5
|FROM pixels
|WHERE col1 IN (col1_v1, col1_v2, ...)
""".stripMargin
val result = sqlContext.sql(query)
// reformat the timestamps
val result2 = result.map(
row => {
val timestamp = row.getAs[String](0).stripSuffix("Z").replace("T"," ")
Row(timestamp, row(1), row(2), row(3), row(4), row(5), row(6), row(7),
row(8), row(9), row(10), row(11))
}
)
// output the result to a csv and remove the square bracket in each row
val output_file = "/root/target"
result2.map(row => row.mkString(",")).saveAsTextFile(output_file)
假设你的json数据如下,
{ "c1": "timestamp_1", "c2": "12", "c3": "13", "c": "14", "c5": "15", ... }
{ "c1": "timestamp_1", "c2": "22", "c3": "23", "c": "24", "c5": "25", ... }
{ "c1": "timestamp_1", "c2": "32", "c3": "33", "c": "34", "c5": "35", ... }
现在,您可以使用json库和RDD来进行转换转储。
import play.api.libs.json._
val data = sc.textFile("abcdefg.txt.gz")
val jsonData = data.map(line => Json.parse(line))
// filter the rdd and just keep the values of interest
val filteredData = data
.filter(json => {
val c1 = (json "c1").as[String]
List[String]("c1_val1", "c2_val2", ...).contains(c1)
})
// reformat the timestamps and transform to tuple
val result2 = filteredData
.map(json => {
val ts = (json "c1").as[String]
val tsFormated = ts.stripSuffix("Z").replace("T"," ")
(tsFormated, (json "c2").as[String], ...)
})
val output_file = "/root/target"
result2.saveAsTextFile(output_file)
处理json的简单方法:
val path = "examples/src/main/resources/people.json"
val peopleDF = spark.read.json(path)
peopleDF.printSchema()
peopleDF.createOrReplaceTempView("people")
val teenagerNamesDF = spark.sql("SELECT name FROM people WHERE age BETWEEN 13 AND 19") teenagerNamesDF.show()
val otherPeopleRDD = spark.sparkContext.makeRDD( """{"name":"Yin","address":{"city":"Columbus","state":"Ohio"}}""" :: Nil) val otherPeople = spark.read.json(otherPeopleRDD) otherPeople.show()
参见doc: http://spark.apache.org/docs/latest/sql-programming-guide.html#json-datasets