【问题标题】:how to extract the column name and data type from nested struct type in spark如何从spark中的嵌套结构类型中提取列名和数据类型
【发布时间】:2017-02-09 05:44:48
【问题描述】:

如何从spark中的嵌套结构类型中提取列名和数据类型

架构是这样的:

(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)

你能帮忙吗

【问题讨论】:

  • phase 来自哪里?它没有出现在输入中。

标签: scala apache-spark


【解决方案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))

【讨论】:

    【解决方案2】:

    如果您有一个带有 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)
    

    【讨论】:

      【解决方案3】:

      假设您将 df1 和 df2 作为两个数据帧,并且您想要比较字段,

      df1.schema.foreach(schema_1=>{ 
        df2.schema.foreach(schema_2=>{ 
        // **to Compare The names**
        if(schema_1.name.equals(schema_2.name)){ // to Compare The names
                // **comparing the data Type**
                 print(schema_1.dataType.equals(schema_2.dataType))
      
        }
      }) 
      })
      

      【讨论】:

        猜你喜欢
        • 2021-12-10
        • 2021-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-26
        • 2018-06-24
        • 1970-01-01
        相关资源
        最近更新 更多