2016-08-03 4 views
8

Mam dataframe o następującej strukturze:Jak spłaszczyć strukturę w iskrowegowej ramce danych?

|-- data: struct (nullable = true) 
| |-- id: long (nullable = true) 
| |-- keyNote: struct (nullable = true) 
| | |-- key: string (nullable = true) 
| | |-- note: string (nullable = true) 
| |-- details: map (nullable = true) 
| | |-- key: string 
| | |-- value: string (valueContainsNull = true) 

Jak to jest możliwe, aby spłaszczyć strukturę i stworzyć nową dataframe:

 |-- id: long (nullable = true) 
    |-- keyNote: struct (nullable = true) 
    | |-- key: string (nullable = true) 
    | |-- note: string (nullable = true) 
    |-- details: map (nullable = true) 
    | |-- key: string 
    | |-- value: string (valueContainsNull = true) 

Czy istnieje coś takiego jak wybuch, ale na elemencie?

+0

Pomocne były również odpowiedzi na https://stackoverflow.com/questions/37471346/automatically-and-elegantly-flatten-dataframe-in-spark-sql. – erwaman

Odpowiedz

21

To powinno działać w Spark 1.6 lub nowszym:

df.select(df.col("data.*")) 

lub

df.select(df.col("data.id"), df.col("data.keyNote"), df.col("data.details")) 
+3

Wyjątek w wątku "główny" org.apache.spark.sql.AnalysisException: Brak takiego pola struct * – djWann

+0

, ale użycie polecenia select we wszystkich kolumnach, takich jak df.select (df.col1, df.col2, df.col3), działa, więc Przyjmuję tę odpowiedź – djWann

+0

Po prostu edytowałem, ale to jest dziwne. Mogę użyć *. Może jakiś problem z wersją? –

1

Łatwym sposobem jest użycie SQL, można zbudować ciąg kwerendy SQL alias zagnieżdżone kolumn jako płaskie te .

  1. pobrać schemat danych ramki (df.schema())
  2. Transform schematu SQL (dla (field. Schema (Pola)()) ....
  3. Query „val newDF = sqlContext.sql ("WYBIERZ" + sqlGenerated + "z ręki")

Przykładem Java:

https://gist.github.com/ebuildy/3de0e2855498e5358e4eed1a4f72ea48

(Preferuję sposób SQL, więc można go łatwo przetestować na Spark-shell i jest to wersja wielojęzyczna).