使用向后兼容模式读取 Spark 中的旧数据

Reading old data in Spark with backward compatible schema

我已经将一些旧数据存储在 parquet 中,其架构由

表示
case class A(name: String)

我想在

中添加一个新的非必填字段
case class B(name: String, age: Option[Int])

并将新旧数据读入同一个DataFrame。每次我尝试使用 spark.read.parquet("test_path").as[B].collect() 读取数据时,都会出现以下异常:

Exception in thread "main" org.apache.spark.sql.AnalysisException: cannot resolve '`age`' given input columns: [name];

有没有办法为我的所有数据指定向后兼容的架构?

为了使用向后兼容的架构读取旧数据,仅指定新的 Encoder 是不够的,您必须为 DataSet 手动指定 StructType,并且不要让 Spark 根据 .这样在转换成 DataFrame:

的过程中就不会丢失字段

spark.read.schema(Encoders.product[B].schema).parquet("test").as[B].collect()