【问题标题】:how to parse the wiki infobox json with scala spark如何使用 scala spark 解析 wiki infobox json
【发布时间】:2017-02-11 20:09:25
【问题描述】:

我试图从我从 wiki api 获得的 json 数据中获取数据

https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=Rajanna&rvsection=0

我能够准确地打印出它的架构

scala> data.printSchema
root
 |-- batchcomplete: string (nullable = true)
 |-- query: struct (nullable = true)
 |    |-- pages: struct (nullable = true)
 |    |    |-- 28597189: struct (nullable = true)
 |    |    |    |-- ns: long (nullable = true)
 |    |    |    |-- pageid: long (nullable = true)
 |    |    |    |-- revisions: array (nullable = true)
 |    |    |    |    |-- element: struct (containsNull = true)
 |    |    |    |    |    |-- *: string (nullable = true)    
 |    |    |    |    |    |-- contentformat: string (nullable = true)
 |    |    |    |    |    |-- contentmodel: string (nullable = true)
 |    |    |    |-- title: string (nullable = true)

我要提取键“*”|-- *: string (nullable = true)的数据 请给我一个解决方案。

一个问题是

pages: struct (nullable = true)
     |    |    |-- 28597189: struct (nullable = true)

数字 28597189 对于每个标题都是唯一的。

【问题讨论】:

    标签: json scala apache-spark


    【解决方案1】:

    首先,我们需要解析 json 以动态获取密钥 (28597189),然后使用它从 spark 数据帧中提取数据,如下所示

    val keyName = dataFrame.selectExpr("query.pages.*").schema.fieldNames(0)
    println(s"Key Name : $keyName")
    

    这将动态地为您提供密钥:

    Key Name : 28597189
    

    然后用这个来提取数据

    var revDf = dataFrame.select(explode(dataFrame(s"query.pages.$keyName.revisions")).as("revision")).select("revision.*")
    revDf.printSchema()
    

    输出:

    root
     |-- *: string (nullable = true)
     |-- contentformat: string (nullable = true)
     |-- contentmodel: string (nullable = true)
    

    我们将重命名列 * 并使用一些键名,例如 star_column

    revDf = revDf.withColumnRenamed("*", "star_column")
    revDf.printSchema()
    

    输出:

    root
     |-- star_column: string (nullable = true)
     |-- contentformat: string (nullable = true)
     |-- contentmodel: string (nullable = true)
    

    一旦我们有了最终的数据框,我们将调用show

    revDf.show()
    

    输出:

    +--------------------+-------------+------------+
    |         star_column|contentformat|contentmodel|
    +--------------------+-------------+------------+
    |{{EngvarB|date=Se...|  text/x-wiki|    wikitext|
    +--------------------+-------------+------------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-19
      • 1970-01-01
      • 2020-08-23
      • 2017-07-23
      • 2016-12-16
      • 1970-01-01
      • 2020-12-15
      • 2016-04-11
      相关资源
      最近更新 更多