代码之家  ›  专栏  ›  技术社区  ›  Milad Khajavi

为什么在使用case类编码JSON时会出现“找不到数据集中存储的类型的编码器”错误?

  •  18
  • Milad Khajavi  · 技术社区  · 9 年前

    我写过spark job:

    object SimpleApp {
      def main(args: Array[String]) {
        val conf = new SparkConf().setAppName("Simple Application").setMaster("local")
        val sc = new SparkContext(conf)
        val ctx = new org.apache.spark.sql.SQLContext(sc)
        import ctx.implicits._
    
        case class Person(age: Long, city: String, id: String, lname: String, name: String, sex: String)
        case class Person2(name: String, age: Long, city: String)
    
        val persons = ctx.read.json("/tmp/persons.json").as[Person]
        persons.printSchema()
      }
    }
    

    在IDE中,当我运行main函数时,会出现2个错误:

    Error:(15, 67) 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.
        val persons = ctx.read.json("/tmp/persons.json").as[Person]
                                                                      ^
    
    Error:(15, 67) not enough arguments for method as: (implicit evidence$1: org.apache.spark.sql.Encoder[Person])org.apache.spark.sql.Dataset[Person].
    Unspecified value parameter evidence$1.
        val persons = ctx.read.json("/tmp/persons.json").as[Person]
                                                                      ^
    

    但在Spark Shell中,我可以毫无错误地运行此作业。问题是什么?

    3 回复  |  直到 6 年前
        1
  •  37
  •   Jacek Laskowski    8 年前

    错误消息显示 Encoder 无法接受 Person case类。

    Error:(15, 67) 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.
    

    将case类的声明移到 SimpleApp .

        2
  •  4
  •   Paul Leclercq    7 年前

    如果您添加 sqlContext.implicits._ spark.implicits._ 在里面 SimpleApp (顺序无关紧要)。

    移除其中一个或另一个将是解决方案:

    val spark = SparkSession
      .builder()
      .getOrCreate()
    
    val sqlContext = spark.sqlContext
    import sqlContext.implicits._ //sqlContext OR spark implicits
    //import spark.implicits._ //sqlContext OR spark implicits
    
    case class Person(age: Long, city: String)
    val persons = ctx.read.json("/tmp/persons.json").as[Person]
    

    使用测试 火花2.1.0

    有趣的是,如果你两次添加相同的对象暗示,你就不会有问题。

        3
  •  3
  •   Santhoshm    6 年前

    @米拉德·哈哈维

    在对象SimpleApp外部定义Person案例类。 另外,添加import-sqlContext.implicits。_main()函数内部。