【问题标题】:Spark Scala Dataframe convert a column of Array of Struct to a column of MapSpark Scala Dataframe 将 Array 的一列转换为 Map 的一列
【发布时间】:2017-07-14 18:06:51
【问题描述】:

我是 Scala 新手。 我有一个带字段的数据框

ID:string, Time:timestamp, Items:array(struct(name:string,ranking:long))

我想将 Items 字段的每一行转换为一个 hashmap,以 name 为键。 我不太清楚该怎么做。

【问题讨论】:

    标签: scala apache-spark apache-spark-sql


    【解决方案1】:

    这可以使用 UDF 来完成:

    import spark.implicits._
    import org.apache.spark.sql.functions._
    import org.apache.spark.sql.Row
    
    // Sample data:
    val df = Seq(
      ("id1", "t1", Array(("n1", 4L), ("n2", 5L))),
      ("id2", "t2", Array(("n3", 6L), ("n4", 7L)))
    ).toDF("ID", "Time", "Items")
    
    // Create UDF converting array of (String, Long) structs to Map[String, Long]
    val arrayToMap = udf[Map[String, Long], Seq[Row]] {
      array => array.map { case Row(key: String, value: Long) => (key, value) }.toMap
    }
    
    // apply UDF
    val result = df.withColumn("Items", arrayToMap($"Items"))
    
    result.show(false)
    // +---+----+---------------------+
    // |ID |Time|Items                |
    // +---+----+---------------------+
    // |id1|t1  |Map(n1 -> 4, n2 -> 5)|
    // |id2|t2  |Map(n3 -> 6, n4 -> 7)|
    // +---+----+---------------------+
    

    如果没有 UDF(仅使用 Spark 的内置函数),我看不到任何方法。

    【讨论】:

      【解决方案2】:

      从2.4.0开始,可以使用map_from_entries

      import spark.implicits._
      import org.apache.spark.sql.functions._
      
      val df = Seq(
        (Array(("n1", 4L), ("n2", 5L))),
        (Array(("n3", 6L), ("n4", 7L)))
      ).toDF("Items")
      
      df.select(map_from_entries($"Items")).show
      
      /*
      +-----------------------+
      |map_from_entries(Items)|
      +-----------------------+
      |     [n1 -> 4, n2 -> 5]|
      |     [n3 -> 6, n4 -> 7]|
      +-----------------------+
      */
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-22
        • 2017-05-20
        • 2017-02-20
        相关资源
        最近更新 更多