【问题标题】:Loading JSON dataset into Spark, then use filter, map, etc将 JSON 数据集加载到 Spark 中,然后使用过滤器、映射等
【发布时间】:2015-03-11 21:32:35
【问题描述】:

我是 Apache Spark 的新手,想获取保存在 JSON 中的数据集(字典列表),将其加载到 RDD 中,然后应用过滤器和映射等操作。在我看来,这应该很简单,但是在查看 Spark 的文档后,我发现唯一使用 SQL 查询 (https://spark.apache.org/docs/1.1.0/sql-programming-guide.html),这不是我想要与 RDD 交互的方式。

如何将保存在 JSON 中的数据集加载到 RDD 中?如果我错过了相关文档,我将不胜感激。

谢谢!

【问题讨论】:

  • 同一文档说使用 SQL 只是一种选择:您可以使用 jsonRDD 以分层方式查询数据。 val anotherPeopleRDD = sc.parallelize( """{"name":"Yin","address":{"city":"Columbus","state":"Ohio"}}""" :: Nil); val anotherPeople = sqlContext.jsonRDD(anotherPeopleRDD)

标签: python json apache-spark


【解决方案1】:

你可以这样做

import org.json4s.JValue
import org.json4s.native.JsonMethods._

val jsonData: RDD[JValue] = sc.textFile(path).flatMap(parseOpt)

然后对该 JValue 进行 JSON 处理,例如

jsonData.foreach(json => {
  println(json \ "someKey")
  (json \ "id") match {
    case JInt(x) => ???
    case _ => ???
})

【讨论】:

    【解决方案2】:

    您是否尝试过在映射中应用 json.loads()?

    import json
    f = sc.textFile('/path/to/file')
    d = lines.map(lambda line: json.loads(line))
    

    【讨论】:

    • 基本上这就是我所做的,是的。我将文件作为原始文本逐行读取,并应用 json.loads 函数。感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 2017-04-28
    • 1970-01-01
    • 2021-05-16
    相关资源
    最近更新 更多