[英]how to parse the wiki infobox json with scala spark
我試圖從Wiki API獲取的json數據中獲取數據
我能夠完全打印出該模式
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以動態獲取密鑰(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|
+--------------------+-------------+------------+
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.