Benennen Sie Spark Dataframe structType-Felder um

Aug 25 2020

Gegeben ein dynamischer structType. hier ist structType name nicht bekannt. Es ist dynamisch und daher ändert sich sein Name.

Der Name ist variabel. Nehmen Sie also nicht "MAIN_COL" im Schema an.

root
 |-- MAIN_COL: struct (nullable = true)
 |    |-- a: string (nullable = true)
 |    |-- b: string (nullable = true)
 |    |-- c: string (nullable = true)
 |    |-- d: string (nullable = true)
 |    |-- f: long (nullable = true)
 |    |-- g: long (nullable = true)
 |    |-- h: long (nullable = true)
 |    |-- j: long (nullable = true)

Wie können wir einen dynamischen Code schreiben, um die Felder eines structType mit seinem Namen als Präfix umzubenennen?

root
 |-- MAIN_COL: struct (nullable = true)
 |    |-- MAIN_COL_a: string (nullable = true)
 |    |-- MAIN_COL_b: string (nullable = true)
 |    |-- MAIN_COL_c: string (nullable = true)
 |    |-- MAIN_COL_d: string (nullable = true)
 |    |-- MAIN_COL_f: long (nullable = true)
 |    |-- MAIN_COL_g: long (nullable = true)
 |    |-- MAIN_COL_h: long (nullable = true)
 |    |-- MAIN_COL_j: long (nullable = true)

Antworten

2 koiralo Aug 25 2020 at 14:30

Sie können DSL verwenden, um das Schema verschachtelter Spalten zu aktualisieren.

import org.apache.spark.sql.types._

val schema: StructType = df.schema.fields.head.dataType.asInstanceOf[StructType]

val updatedSchema = StructType.apply(
       schema.fields.map(sf => StructField.apply("MAIN_COL_" + sf.name, sf.dataType))
)

val resultDF = df.withColumn("MAIN_COL", $"MAIN_COL".cast(updatedSchema))

Aktualisiertes Schema:

root
 |-- MAIN_COL: struct (nullable = false)
 |    |-- MAIN_COL_a: string (nullable = true)
 |    |-- MAIN_COL_b: string (nullable = true)
 |    |-- MAIN_COL_c: string (nullable = true)