2017-02-09 91 views
1

如何火花提取嵌套結構類型的列名和數據類型如何在火花

模式,得到了下面提取嵌套的結構類型的列名和數據類型:

(events,StructType(
    StructField(beaconType,StringType,true),  
    StructField(beaconVersion,StringType,true), 
    StructField(client,StringType,true), 
    StructField(data,StructType(
     StructField(ad,StructType(
     StructField(adId,StringType,true) 
    ) 
    ) 
) 

我要轉換成以下格式

Array[(String, String)] = Array(
    (client,StringType), 
    (beaconType,StringType), 
    (beaconVersion,StringType), 
    (phase,StringType) 

請你對這個

+0

「相位」來自哪裏?它不會出現在輸入中。 –

回答

1

任務幫助離子有點不清楚,但如果您正在尋找一種方法來「平整」DataFrame架構(即,得到所有非結構字段的數組),這裏有一個:

def flatten(schema: StructType): Array[StructField] = schema.fields.flatMap { f => 
    f.dataType match { 
    case struct: StructType => flatten(struct) 
    case _ => Array(f) 
    } 
} 

例如:

val schema = StructType(Seq(StructField("events", 
    StructType(Seq(
    StructField("beaconVersion", IntegerType, true), 
    StructField("client", StringType, true), 
    StructField("data", StructType(Seq(
     StructField("ad", StructType(Seq(
     StructField("adId", StringType, true) 
    ))) 
    ))) 
))) 
)) 

println(flatten(schema).toList) 
// List(StructField(beaconVersion,IntegerType,true), StructField(client,StringType,true), StructField(adId,StringType,true)) 
1

如果你有一個StructType列即數據幀:

df.printSchema() 
// root 
// |-- data: struct (nullable = true) 
// | |-- embedded_data: string (nullable = true) 

你可以提取StructTypedata的子字段embedded_data,如下所示:

df.select("data.embedded_data").printSchema() 
// root 
// |-- data.embedded_data: string (nullable = true)