Apache Spark 2.0:java.lang.UnsupportedOperationException:找不到java.time.LocalDate

时间:2016-08-03 09:44:40

标签: scala apache-spark apache-spark-sql apache-spark-dataset apache-spark-encoders

我正在使用Apache Spark 2.0并为case class的提及架构创建DetaSet。当我尝试根据How to store custom objects in Dataset?定义自定义编码器时,java.time.LocalDate我遇到以下异常:

java.lang.UnsupportedOperationException: No Encoder found for java.time.LocalDate
- field (class: "java.time.LocalDate", name: "callDate")
- root class: "FireService"
at org.apache.spark.sql.catalyst.ScalaReflection$.org$apache$spark$sql$catalyst$ScalaReflection$$serializerFor(ScalaReflection.scala:598)
at org.apache.spark.sql.catalyst.ScalaReflection$$anonfun$9.apply(ScalaReflection.scala:592)
at org.apache.spark.sql.catalyst.ScalaReflection$$anonfun$9.apply(ScalaReflection.scala:583)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
at scala.collection.immutable.List.foreach(List.scala:381)
at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
............

以下是代码:

case class FireService(callNumber: String, callDate: java.time.LocalDate)
implicit val localDateEncoder: org.apache.spark.sql.Encoder[java.time.LocalDate] = org.apache.spark.sql.Encoders.kryo[java.time.LocalDate]

val fireServiceDf = df.map(row => {
val dateFormatter = java.time.format.DateTimeFormatter.ofPattern("MM/dd /yyyy")
FireService(row.getAs[String](0),  java.time.LocalDate.parse(row.getAs[String](4), dateFormatter))
})

我们如何为spark定义第三方api的编码器?

更新

当我为整个案例类创建编码器时,df.map..将对象映射为二进制,如下所示:

implicit val fireServiceEncoder: org.apache.spark.sql.Encoder[FireService] = org.apache.spark.sql.Encoders.kryo[FireService]

val fireServiceDf = df.map(row => {
 val dateFormatter = java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy")
 FireService(row.getAs[String](0), java.time.LocalDate.parse(row.getAs[String](4), dateFormatter))
})

fireServiceDf: org.apache.spark.sql.Dataset[FireService] = [value: binary]

我期待FireService的地图,但返回地图的二进制文件。

1 个答案:

答案 0 :(得分:5)

正如最后一条评论所说,“如果类包含字段条,则需要整个对象的编码器。”您需要为FireService本身提供隐式编码器;否则Spark使用SQLImplicits.newProductEncoder[T <: Product : TypeTag]: Encoder[T]为您构建一个。您可以从类型中看到它不对字段使用任何implicit编码器参数,因此它不能使用localDateEncoder的存在。

可以更改Spark以处理此问题,例如使用Shapeless库,或直接使用宏;我不知道这是否是未来的计划。