【问题标题】:Spark DataFrame exploding a map with the key as a memberSpark DataFrame以键为成员爆炸地图
【发布时间】:2017-05-26 03:10:57
【问题描述】:

我在databrick's blog找到了一个地图爆炸示例:

// input
{
  "a": {
    "b": 1,
    "c": 2
  }
}

Python: events.select(explode("a").alias("x", "y"))
 Scala: events.select(explode('a) as Seq("x", "y"))
   SQL: select explode(a) as (x, y) from events

// output
[{ "x": "b", "y": 1 }, { "x": "c", "y": 2 }]

但是,我看不出有什么方法可以让我将地图更改为一个数组,其中键被展平,然后分解:

// input
{
  "id": 0,
  "a": {
    "b": {"d": 1, "e": 2}
    "c": {"d": 3, "e": 4}
  }
}
// Schema
struct<id:bigint,a:map<string,struct<d:bigint,e:bigint>>>
root
 |-- id: long (nullable = true)
 |-- a: map (nullable = true)
 |    |-- key: string
 |    |-- value: struct (valueContainsNull = true)
 |    |    |-- d: long (nullable = true)
 |    |    |-- e: long (nullable = true)


// Imagined proces
Python: …
 Scala: events.select('id, explode('a) as Seq("x", "*")) //? "*" ?
   SQL: …

// Desired output
[{ "id": 0, "x": "b", "d": 1, "e": 2 }, { "id": 0, "x": "c", "d": 3, "e": 4 }]

有没有一些明显的方式可以让人们接受这样的输入来制作一个表格,比如:

id | x | d | e
---|---|---|---
 0 | b | 1 | 2
 0 | c | 3 | 4

【问题讨论】:

  • 如果我理解你的问题,你可以在 JSON 字符串上使用 from_json 来获取表(数据框)。
  • @mrsrinivas 谢谢,但在这种情况下它是一个镶木地板文件,其中包含地图。
  • from_json 将 json 字符串(不是文件)转换为数据帧

标签: apache-spark exploded


【解决方案1】:

虽然我不知道是否可以用一个explode 来炸毁地图,但有一种方法可以使用UDF。诀窍是使用Row#schema.fields(i).name 来获取“密钥”的名称

def mapStructs = udf((r: Row) => {
  r.schema.fields.map(f => (
    f.name,
    r.getAs[Row](f.name).getAs[Long]("d"),
    r.getAs[Row](f.name).getAs[Long]("e"))
  )
})

df
  .withColumn("udfResult", explode(mapStructs($"a")))
  .withColumn("x", $"udfResult._1")
  .withColumn("d", $"udfResult._2")
  .withColumn("e", $"udfResult._3")
  .drop($"udfResult")
  .drop($"a")
  .show

给予

+---+---+---+---+
| id|  x|  d|  e|
+---+---+---+---+
|  0|  b|  1|  2|
|  0|  c|  3|  4|
+---+---+---+---+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2018-04-27
    • 2022-06-18
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多