2017-02-09 2 views
0

ich die Daten von JSON-Daten zu bekommen versuche, die ich aus dem Wiki api bekamwie die Wiki infobox json mit scala Funken analysieren

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

ich in der Lage war, das Schema dieser genau zu drucken

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) 

ich möchte die Daten des Schlüssels extrahieren „*“ |-- *: string (nullable = true) Bitte empfehlen Sie mir eine Lösung.

Ein Problem ist

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

die Zahl 28.597.189 zu jedem Titel einzigartig ist.

Antwort

1

Zunächst müssen wir die json analysieren, um die Schlüssel (28597189) zu erhalten dynamisch dann diese verwenden, um die Daten von Funkendatenrahmen wie zu extrahieren unter

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

das Sie dynamisch den Schlüssel geben:

Key Name : 28597189 

Dann ist diese verwenden, um die Daten zu extrahieren

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

Ausgang:

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

und wir werden die Spalt * mit einigen Schlüsselnamen wie star_column

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

Ausgabe werden die Umbenennung:

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

und sobald wir unseren letzten Datenrahmen haben wir nennen show

revDf.show() 

Ausgabe:

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