Scala Spark - 用于map(String,Int)的DataFrame列上的空映射

时间:2017-11-04 14:29:48

标签: scala dictionary apache-spark dataframe

我正在加入两个DataFrame,其中有Map[String, Int]

类型的列

我希望合并的DF在[]类型列上有一个空地图null而不是Map

val df = dfmerged.
  .select("id"),
          coalesce(col("map_1"), lit(null).cast(MapType(StringType, IntType))).alias("map_1"),
          coalesce(col("map_2"), lit(Map.empty[String, Int])).alias("map_2")

对于map_1列,我会插入null,但我想要空地图 map_2给了我一个错误:

  

java.lang.RuntimeException:不支持的文字类型类   scala.collection.immutable.Map $ EmptyMap $ Map()

我也试过udf函数,如:

case class myStructMap(x:Map[String, Int])
val emptyMap = udf(() => myStructMap(Map.empty[String, Int]))

也没用。

当我尝试类似的事情时:

.select( coalesce(col("myMapCol"), lit(map())).alias("brand_viewed_count")...

.select(coalesce(col("myMapCol"), lit(map().cast(MapType(LongType, LongType)))).alias("brand_viewed_count")...

我收到错误:

  由于数据类型不匹配,

无法解析'map()':无法强制转换   MapType(NullType,NullType,false)到MapType(LongType,IntType,true);

1 个答案:

答案 0 :(得分:4)

在Spark 2.2中

df.withColumn("map", coalesce($"map", map().cast("map<string,int>"))).show
// +---+-----------------+
// | id|              map|
// +---+-----------------+
// |  1|            Map()|
// |  2|Map(foobar -> 42)|
// +---+-----------------+

position:relative;