【问题标题】:Error while exploding a struct column in Spark在 Spark 中爆炸结构列时出错
【发布时间】:2018-06-27 04:19:22
【问题描述】:

我有一个数据框,其架构如下所示:

event: struct (nullable = true)
|    | event_category: string (nullable = true)
|    | event_name: string (nullable = true)
|    | properties: struct (nullable = true)
|    |    | ErrorCode: string (nullable = true)
|    |    | ErrorDescription: string (nullable = true)

我正在尝试使用以下代码分解structproperties

df_json.withColumn("event_properties", explode($"event.properties"))

但它抛出了以下异常:

cannot resolve 'explode(`event`.`properties`)' due to data type mismatch: 
input to function explode should be array or map type, 
not StructType(StructField(IDFA,StringType,true),

如何爆列properties

【问题讨论】:

  • @user8371915 由于该问题已被标记为该问题的重复,您的近距离投票现在将导致循环重复导航(如果现在尝试则无效)

标签: scala apache-spark pyspark apache-spark-sql spark-dataframe


【解决方案1】:

正如错误消息所说,您只能分解数组或映射类型,而不能分解结构类型列。

你可以这样做

df_json.withColumn("event_properties", $"event.properties")

这将生成一个新列event_properties,它也是struct-type的

如果要将结构的每个元素转换为新列,则不能使用withColumn,需要使用select 和通配符*

df_json.select($"event.properties.*")

【讨论】:

    【解决方案2】:

    您可以使用以下来展平结构。 Explode 不适用于 struct 作为错误消息状态。

    val explodeDF = parquetDF.explode($"event") { 
    case Row(properties: Seq[Row]) => properties.map{ property =>
      val errorCode = property(0).asInstanceOf[String]
      val errorDescription = property(1).asInstanceOf[String]
      Event(errorCode, errorDescription, email, salary)
     }
    }.cache()
    display(explodeDF)
    

    【讨论】:

      【解决方案3】:

      您可以在arraymap 列中使用explode 因此您需要将properties struct 转换为array,然后应用explode 函数如下

      import org.apache.spark.sql.functions._
      df_json.withColumn("event_properties", explode(array($"event.properties.*"))).show(false)
      

      你应该有你想要的要求

      【讨论】:

      • 如何像地图一样爆炸。我也需要键名
      猜你喜欢
      • 2018-04-27
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      • 1970-01-01
      相关资源
      最近更新 更多