เปลี่ยนชื่อฟิลด์ spark dataframe structType
Aug 25 2020
กำหนดโครงสร้างแบบไดนามิก ที่นี่ไม่รู้จักชื่อ structType มันเป็นแบบไดนามิกและด้วยเหตุนี้ชื่อจึงเปลี่ยนไป
ชื่อเป็นตัวแปร ดังนั้นอย่าคาดเดา "MAIN_COL" ไว้ล่วงหน้าในสคีมา
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)
เราจะเขียนโค้ดแบบไดนามิกเพื่อเปลี่ยนชื่อฟิลด์ของ structType โดยใช้ชื่อเป็นคำนำหน้าได้อย่างไร
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)
คำตอบ
2 koiralo Aug 25 2020 at 14:30
คุณสามารถใช้ DSL เพื่ออัปเดตสคีมาของคอลัมน์ที่ซ้อนกัน
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))
สคีมาที่อัปเดต:
root
|-- MAIN_COL: struct (nullable = false)
| |-- MAIN_COL_a: string (nullable = true)
| |-- MAIN_COL_b: string (nullable = true)
| |-- MAIN_COL_c: string (nullable = true)