【问题标题】:Scala Spark - empty map on DataFrame column for map(String, Int)Scala Spark - 地图的DataFrame列上的空地图(String,Int)
【发布时间】:2018-04-17 03:07:56
【问题描述】:

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

我希望合并的 DF 在 Map 类型列上有一个空映射 [] 而不是 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);

【问题讨论】:

    标签: scala dictionary apache-spark dataframe


    【解决方案1】:

    在 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)|
    // +---+-----------------+
    

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      • 2019-12-09
      • 1970-01-01
      相关资源
      最近更新 更多