gpt4 book ai didi

json - 在 Spark 中快速处理 json 文件的方法

转载 作者:行者123 更新时间:2023-12-01 06:23:58 27 4
gpt4 key购买 nike

我有一组带有嵌套键值对的大型压缩 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 - 在 Spark 中快速处理 json 文件的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38909120/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com