如何创建地图数据集? [英] How to create a Dataset of Maps?

查看:123
本文介绍了如何创建地图数据集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spark 2.2,尝试在MapSeq上调用spark.createDataset时遇到麻烦.

I'm using Spark 2.2 and am running into troubles when attempting to call spark.createDataset on a Seq of Map.

Spark Shell会话中的代码和输出如下:

Code and output from my Spark Shell session follow:

// createDataSet on Seq[T] where T = Int works
scala> spark.createDataset(Seq(1, 2, 3)).collect
res0: Array[Int] = Array(1, 2, 3)

scala> spark.createDataset(Seq(Map(1 -> 2))).collect
<console>:24: error: 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.
       spark.createDataset(Seq(Map(1 -> 2))).collect
                          ^

// createDataSet on a custom case class containing Map works
scala> case class MapHolder(m: Map[Int, Int])
defined class MapHolder

scala> spark.createDataset(Seq(MapHolder(Map(1 -> 2)))).collect
res2: Array[MapHolder] = Array(MapHolder(Map(1 -> 2)))

我已经尝试过import spark.implicits._,尽管我相当确定它是由Spark shell会话隐式导入的.

I've tried import spark.implicits._, though I'm fairly certain that's implicitly imported by the Spark shell session.

这是当前编码器无法解决的情况吗?

Is this is a case not covered by current encoders?

推荐答案

2.2中未涉及它,但可以轻松解决.您可以使用ExpressionEncoder显式添加所需的Encoder:

It is not covered in 2.2, but can be easily addressed. You can add required Encoder using ExpressionEncoder, either explicitly:

import org.apache.spark.sql.catalyst.encoders.ExpressionEncoder  
import org.apache.spark.sql.Encoder

spark
  .createDataset(Seq(Map(1 -> 2)))(ExpressionEncoder(): Encoder[Map[Int, Int]])

implicitly:

implicit def mapIntIntEncoder: Encoder[Map[Int, Int]] = ExpressionEncoder()
spark.createDataset(Seq(Map(1 -> 2)))

这篇关于如何创建地图数据集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆