[英]Error while saving map value in Spark dataframe(scala) - Expected column, actual Map[int,string]
[英]Scala Spark - empty map on DataFrame column for map(String, Int)
我正在加入两个DataFrame,其中有类型为Map[String, Int]
我希望合并的DF具有一个空的map []
并且在Map
type列上不为null
。
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);
在Spark 2.2中
import org.apache.spark.sql.functions.typedLit
val df = Seq((1L, null), (2L, Map("foo" -> "bar"))).toDF("id", "map")
df.withColumn("map", coalesce($"map", typedLit(Map[String, Int]()))).show
// +---+-----------------+
// | id| map|
// +---+-----------------+
// | 1| Map()|
// | 2|Map(foobar -> 42)|
// +---+-----------------+
之前
df.withColumn("map", coalesce($"map", map().cast("map<string,int>"))).show
// +---+-----------------+
// | id| map|
// +---+-----------------+
// | 1| Map()|
// | 2|Map(foobar -> 42)|
// +---+-----------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.