2016-08-12 11 views
2

我有一组使用嵌套键值对的大型压缩json文件。 json对象中有大约70-80个键(和子键),但是,我只对几个键感兴趣。我想用Spark SQL查询json文件,只挑出我感兴趣的键值对,并将它们输出到一组csv文件。处理一个大小为170MB的压缩json文件需要大约5分钟的时间。我只是想知道是否有任何方法来优化这个过程。或者除了Spark这样的工作,还有其他更好的工具吗?谢谢!快速处理Spark中的json文件的方法

下面是我用的是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) 
+0

我;猜大部分时间的推移读/解压缩和写作,这不能并行化。添加分配作业和收集结果的开销,我的猜测是使用Spark会让你放慢速度。为什么未分析的行的“重新分配”? –

+0

如果你只是想改变你的数据。你不需要所有的SparkSQL功能。只要坚持RDD的。使用像PlayJson这样的快速json库来解析json。修改并转储它。 –

+0

除非明确要求,否则请勿对RDD进行重新分区。 –

回答

2

比方说你的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 lib和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) 
0

很简单的方法来处理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() 

见文件:http://spark.apache.org/docs/latest/sql-programming-guide.html#json-datasets

+0

此回答有用吗? – pacman