星火斯卡拉数据集类型层次

问题描述 投票:0回答:1

试图强制执行W延伸有一个返回WR的子类的数据集的方法获取类。

abstract class WR

case class TGWR(
          a: String,
          b: String
        ) extends WR

abstract class W {

  def get[T <: WR](): Dataset[T]

}


class TGW(sparkSession: SparkSession) extends W {

  override def get[TGWR](): Dataset[TGWR] = {
    import sparkSession.implicits._

    Seq(TGWR("dd","dd").toDF().as[TGWR]
  }

}

编译错误:

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

如果我改变了get功能如下:

  def get(): Dataset[TGWR]

  override def get(): Dataset[TGWR] = {...

它编译 - 因此,我怀疑有问题,由于继承/类型层次。

scala apache-spark apache-spark-dataset apache-spark-encoders
1个回答
2
投票

忘记我的评论,我重读你的问题,发现一个简单的问题。

这里override def get[TGWR]你是不是说这个类产生的TGWR的实例,但要创建名TGWR的新类型参数,将影子你真正的类型。 我用下面的代码固定它:

import org.apache.spark.sql.{SparkSession, Dataset}

abstract class WR extends Product with Serializable

final case class TGWR(a: String, b: String) extends WR

abstract class W[T <: WR] {
  def get(): Dataset[T]
}

final class TGW(spark: SparkSession) extends W[TGWR] {
  override def get(): Dataset[TGWR] = {
    import spark.implicits._
    Seq(TGWR("dd","dd")).toDF().as[TGWR]
  }
}

您可以使用此权:

val spark = SparkSession.builder.master("local[*]").getOrCreate()
(new TGW(spark)).get()
// res1: org.apache.spark.sql.Dataset[TGWR] = [a: string, b: string]
res1.show()
// +---+---+
// |  a|  b|
// +---+---+
// | dd| dd|
// +---+---+

希望这是你在找什么。 不要怀疑,要求澄清。

© www.soinside.com 2019 - 2024. All rights reserved.