没有隐含类型 T 的参数,试图将数据帧转换为数据集 [T]

No implicits arguments of type T, Trying to cast a dataframe to a Dataset[T]

我正在尝试构建一个通用函数来合并一些 mongoDb 集合,我使用 case classes 来键入集合,并且在我的函数中我接收类型作为参数[T] 像这样:

  def refreshCollection[T](newDS:Dataset[T],oldDS:Dataset[T]): Dataset[T]={
    val filteredOldDS=oldDS.join(newDS, Seq("id"),"left_anti").as[T]
    filteredOldDS.union(newDS)
  }

问题是当我尝试使用 .as[T] 将连接的 Dataframe 结果转换为原始案例 class 到 return a Dataset[T] 我有这个错误甚至很难我已经导入了 sparkSession.implicits._:

no implicit arguments of type: Encoder[T]

有趣的是,当我用固定大小写进行转换时 class 工作正常,有什么建议吗?

提前致谢!

我认为这是因为您的代码不能保证 Encoder[T] 在必要时可用。

您可以尝试使用隐式解码器对您的参数进行参数化,并推迟编译器尝试找到所需解码器的时间。

  def refreshCollection[T](newDS:Dataset[T],oldDS:Dataset[T])(implicit enc: Encoder[T]): Dataset[T]={
    val filteredOldDS=oldDS.join(newDS, Seq("id"),"left_anti").as[T]
    filteredOldDS.union(newDS)
  }

当然,您需要在调用 refreshCollection

时以某种方式将 Encoder[MyCaseClass] 纳入范围