【问题标题】:Spark: Unable to find encoder for type UnitSpark:找不到单元类型的编码器
【发布时间】:2021-11-29 02:40:33
【问题描述】:

我有这样的数据框:

ID  Country  Revenue
1     US       1000
2     IND      2000
3     DE       4000

我正在尝试转换为 JSON 格式并写入我的本地路径。

输出

[
  {
    "ID": 1,
    "Country": "US",
    "Revenue": 1000
  },
  {
    "ID": 2,
    "Country": "IND",
    "Revenue": 2000
  },......
]

代码

import spark.implicits._

val DF = spark.sql("select  ID,Country,Revenue from  table")

DF.show()

case class ID(ID:int)

case class country(country:String)

case class Revenue(Revenue:Int)

case class details(ID:ID,country:country,Revenue:Revenue)

val JsonDF= DF.map(r=>{val details_1=details(r.getString(0),r.getString(1),r.getString(2))})

JsonDF.repartition(1).write.option("multiLine","true").json("C:/Desktop/output/revenue.json")

但我收到以下错误:

找不到单元类型的编码器。需要一个隐式 Encoder[Unit] 来将 Unit 实例存储在 Dataset 中。导入 spark.implicits 支持原始类型(Int、String 等)和产品类型(案例类)。_

我的错误在哪里?

【问题讨论】:

  • 你得到什么错误?
  • @GaëlJ 此错误无法找到 Unit 类型的编码器。需要一个隐式 Encoder[Unit] 来将 Unit 实例存储在 Dataset 中。通过导入 spark.implicits._ 支持原始类型(Int、String 等)和产品类型(案例类)

标签: scala apache-spark


【解决方案1】:

找不到 Unit 类型的编码器。

这意味着您在数据集中存储了 Unit 值,这可能不是您想要的,应该是一个提示。

换行:

val JsonDF = DF.map(r=>{val details_1=details(r.getString(0),r.getString(1),r.getString(2))})
// DataSet[Unit]

作者:

val JsonDF = DF.map(r => details(r.getString(0),r.getString(1),r.getString(2)))
// DataSet[details]

在您的原始代码中,您正在创建一个 details 实例,但没有在 lambda 中返回它。

【讨论】:

  • 错误:不明确的隐式值:类型 => org.apache.spark.sql.Encoder[Int] 的类 SQLImplicits 中的方法 newIntEncoder 和类型 => org.apache 的类 SQLImplicits 中的方法 newLongEncoder。 spark.sql.Encoder[Long] 匹配预期类型 org.apache.spark.sql.Encoder[U] val JsonDF = DF.map(r => details(r.getString(0),r.getString(1),r .getString(2)))
  • 我收到此错误
  • 你有自定义的apply 方法用于details 吗?您第一篇文章中的定义是否正确?
  • 在我执行代码时,您能否就给定数据本身的示例脚本向我提出建议。我遇到了问题。
猜你喜欢
  • 2021-05-08
  • 1970-01-01
  • 2016-12-08
  • 2020-07-30
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-16
相关资源
最近更新 更多