如何为 Option 类型构造函数创建编码器,例如选项[Int]?

How to create encoder for Option type constructor, e.g. Option[Int]?

是否可以在与数据集 API 一起使用的案例 class 中使用 Option[_] 成员?例如。 Option[Int]

我试图找到一个例子,但还没有找到。这可能可以通过自定义编码器(映射?)来完成,但我还找不到相关的示例。

这可能可以使用 Frameless 库实现:https://github.com/adelbertc/frameless 但应该有一种简单的方法可以使用基本 Spark 库完成它。

更新

我正在使用:"org.apache.spark" %% "spark-core" % "1.6.1"

尝试使用 Option[Int] 时出现以下错误:

Unable to find encoder for type stored in a Dataset. Primitive types (Int, String, etc) and Product types (case classes) are supported by importing sqlContext.implicits._ Support for serializing other types will be added in future releases

解决方案更新

由于我正在制作原型,所以我只是在转换为数据集之前在函数内部声明大小写 class(在我的例子中是在 object Main { 中)。

当我将大小写 class 移出 Main 函数时,选项类型工作得很好。

"Support for serializing other types will be added in future releases"。自定义编码器尚不支持,但显然已在计划中。你可以尝试自己实现trait,但是肯定没有官方的例子。

一种选择是使用 Seq[Int] 成员并确保它最多只有一个值。

我们只为我们支持的类型的子集定义隐式 in SQLImplicits. We should probably consider adding Option[T] for common T as the internal infrastructure does understand Option. You can workaround this by either creating a case class, using a Tuple or constructing the required implicit yourself(尽管这是使用和内部 API,因此在未来的版本中可能会中断)。

implicit def optionalInt: org.apache.spark.sql.Encoder[Option[Int]] = org.apache.spark.sql.catalyst.encoders.ExpressionEncoder()

val ds = Seq(Some(1), None).toDS()