Scala 如何根据预定义的模式向dataframe添加缺少的字段?

Scala 如何根据预定义的模式向dataframe添加缺少的字段?,scala,apache-spark,apache-spark-sql,Scala,Apache Spark,Apache Spark Sql,在使用spark streaming应用程序时,如果来自kafka的批处理中的所有记录都遗漏了一个公共字段,则dataframe模式每次都会更改。我需要一个固定的数据帧模式来进行进一步的处理和转换操作 我有这样的预定义模式: root |-- PokeId: string (nullable = true) |-- PokemonName: string (nullable = true) |-- PokemonWeight: integer (nullable = false) |--

在使用spark streaming应用程序时,如果来自kafka的批处理中的所有记录都遗漏了一个公共字段,则dataframe模式每次都会更改。我需要一个固定的数据帧模式来进行进一步的处理和转换操作

我有这样的预定义模式:

root
 |-- PokeId: string (nullable = true)
 |-- PokemonName: string (nullable = true)
 |-- PokemonWeight: integer (nullable = false)
 |-- PokemonType: string (nullable = true)
 |-- PokemonEndurance: float (nullable = false)
 |-- Attacks: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- AttackName: string (nullable = true)
 |    |    |-- AttackImpact: long (nullable = true)
val schema = StructType(Array(
  StructField("PokeId", StringType, true),
  StructField("PokemonName", StringType, true),
  StructField("PokemonWeight", IntegerType, false),
  StructField("PokemonType", StringType, true),
  StructField("PokemonEndurance", FloatType, false),
  StructField("Attacks", ArrayType(StructType(Array(
          StructField("AttackName", StringType),
          StructField("AttackImpact", LongType)
        ))))
))
但对于某些流式会话,我不会得到所有列,输入模式如下:

root
 |-- PokeId: string (nullable = true)
 |-- PokemonName: string (nullable = true)
 |-- PokemonWeight: integer (nullable = false)
 |-- PokemonEndurance: float (nullable = false)
我这样定义我的模式:

root
 |-- PokeId: string (nullable = true)
 |-- PokemonName: string (nullable = true)
 |-- PokemonWeight: integer (nullable = false)
 |-- PokemonType: string (nullable = true)
 |-- PokemonEndurance: float (nullable = false)
 |-- Attacks: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- AttackName: string (nullable = true)
 |    |    |-- AttackImpact: long (nullable = true)
val schema = StructType(Array(
  StructField("PokeId", StringType, true),
  StructField("PokemonName", StringType, true),
  StructField("PokemonWeight", IntegerType, false),
  StructField("PokemonType", StringType, true),
  StructField("PokemonEndurance", FloatType, false),
  StructField("Attacks", ArrayType(StructType(Array(
          StructField("AttackName", StringType),
          StructField("AttackImpact", LongType)
        ))))
))
现在,我不知道如何在基于此模式的输入数据帧中添加缺少的列(具有空值)


我已尝试使用进行数据帧验证,但它会将缺少的列作为描述性错误返回。如何从中获取缺少的列。

您可以演示如何使用架构吗?更新了我的问题。我必须对输入数据帧执行数据帧转换操作,若数据帧中不存在某些字段,则会在其余代码中出现错误@谢谢你的更新。您是否可以显示当前版本的代码,该代码使用架构读取数据,并且对于不可用的字段,希望使用
null
s?您可以按此处所示进行架构比较。如果两个数据帧之间的模式不同,则根据更改select语句。您可以演示如何使用该模式吗?更新了我的问题。我必须对输入数据帧执行数据帧转换操作,若数据帧中不存在某些字段,则会在其余代码中出现错误@谢谢你的更新。您是否可以显示当前版本的代码,该代码使用架构读取数据,并且对于不可用的字段,希望使用
null
s?您可以按此处所示进行架构比较。如果两个数据帧之间的模式不同,则相应地更改select语句