我正在尝试实现返回复杂类型的类型化UDAF。 Spark无法以某种方式推断结果列的类型,并使其binary
放置序列化数据。这是一个重现问题的最小示例
import org.apache.spark.sql.expressions.Aggregator
import org.apache.spark.sql.{SparkSession, Encoder, Encoders}
case class Data(key: Int)
class NoopAgg[I] extends Aggregator[I, Map[String, Int], Map[String, Int]] {
override def zero: Map[String, Int] = Map.empty[String, Int]
override def reduce(b: Map[String, Int], a: I): Map[String, Int] = b
override def merge(b1: Map[String, Int], b2: Map[String, Int]): Map[String, Int] = b1
override def finish(reduction: Map[String, Int]): Map[String, Int] = reduction
override def bufferEncoder: Encoder[Map[String, Int]] = Encoders.kryo[Map[String, Int]]
override def outputEncoder: Encoder[Map[String, Int]] = Encoders.kryo[Map[String, Int]]
}
object Question {
def main(args: Array[String]): Unit = {
val spark = SparkSession.builder().master("local").getOrCreate()
val sc = spark.sparkContext
import spark.implicits._
val ds = sc.parallelize((1 to 10).map(i => Data(i))).toDS()
val noop = new NoopAgg[Data]().toColumn
val result = ds.groupByKey(_.key).agg(noop.as("my_sum").as[Map[String, Int]])
result.printSchema()
}
}
它打印
root
|-- value: integer (nullable = false)
|-- my_sum: binary (nullable = true)
答案 0 :(得分:1)
这里根本没有推断。相反,您或多或少会得到您想要的东西。具体的错误在这里:
override def outputEncoder: Encoder[Map[String, Int]] = Encoders.kryo[Map[String, Int]]
Encoders.kryo
表示您应用通用序列化并返回二进制blob。令人误解的部分是.as[Map[String, Int]]
-与人们期望的相反,它不是静态类型检查的。更糟糕的是,查询计划人员甚至没有主动验证它,只有在评估result
时才会抛出运行时异常。
result.first
org.apache.spark.sql.AnalysisException: cannot resolve '`my_sum`' due to data type mismatch: cannot cast binary to map<string,int>;
at org.apache.spark.sql.catalyst.analysis.package$AnalysisErrorAt.failAnalysis(package.scala:42)
at org.apache.spark.sql.catalyst.analysis.CheckAnalysis$$anonfun$checkAnalysis$1$$anonfun$apply$3.applyOrElse(CheckAnalysis.scala:115)
...
您应该提供特定的Encoder
,either explicitly:
import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
def outputEncoder: Encoder[Map[String, Int]] = ExpressionEncoder()
或隐含
class NoopAgg[I](implicit val enc: Encoder[Map[String, Int]]) extends Aggregator[I, Map[String, Int], Map[String, Int]] {
...
override def outputEncoder: Encoder[Map[String, Int]] = enc
}
作为副作用,由于已经知道as[Map[String, Int]]
的返回类型,因此它将使Aggregator
过时。