【问题标题】:How can I split an array of structs into columns in Spark?如何在 Spark 中将结构数组拆分为列?
【发布时间】:2019-08-26 19:15:42
【问题描述】:

我有一列包含表示为结构的电话号码数组,需要通过“type”属性(phone1, phone2, fax) 将它们分成三列。

这是该列的两个示例值。

[{"number":"000-000-0000","type":"Phone1"},{"number":"000-000-0001","type":"Phone2"},{"number":"000-000-0002","type":"Fax"}]
[{"number":"000-000-1000","type":"Phone1"},{"number":"000-000-1001","typeCode":"Fax"},{"number":"000-000-1002","type":"Phone2"}]

我想将每一列分成三列,每种类型一列。 我想要这样的东西:

   Phone1           Phone2           Fax
000-000-0000     000-000-0001     000-000-0002
000-000-1000     000-000-1002     000-000-1001

这个答案展示了如何将数组的每个元素放入自己的列中。 How to explode an array into multiple columns in Spark

这让我走到了一半,但我不能依赖数组中项目的顺序。如果我这样做,我会得到类似的结果,第二列中的 Phone2 和 Fax 值不合适。

   Phone1           Phone2           Fax
000-000-0000     000-000-0001     000-000-0002
000-000-1000     000-000-1001     000-000-1002

如何使用类型值将单列值拆分为三列?一个数组可以有 0-3 个数字,但每种类型的数字永远不会超过一个。

【问题讨论】:

    标签: json scala apache-spark schema


    【解决方案1】:

    这是一种方法,通过explode 将电话/传真#s 展平,然后在typeCode 上进行旋转,如下例所示:

    case class Contact(number: String, typeCode: String)
    
    val df = Seq(
      (1, Seq(Contact("111-22-3333", "Phone1"), Contact("111-44-5555", "Phone2"), Contact("111-66-7070", "Fax"))),
      (2, Seq(Contact("222-33-4444", "Phone1"), Contact("222-55-6060", "Fax"), Contact("111-77-8888", "Phone2")))
    ).toDF("user_id", "contacts")
    
    df.
      withColumn("contact", explode($"contacts")).
      groupBy($"user_id").pivot($"contact.typeCode").agg(first($"contact.number")).
      show(false)
    // +-------+-----------+-----------+-----------+
    // |user_id|Fax        |Phone1     |Phone2     |
    // +-------+-----------+-----------+-----------+
    // |1      |111-66-7070|111-22-3333|111-44-5555|
    // |2      |222-55-6060|222-33-4444|111-77-8888|
    // +-------+-----------+-----------+-----------+
    

    【讨论】:

    • 如果 DF 包含要保留的其他列怎么办?可以将它们添加到groupBy 子句中,但这不适用于像 MapType 这样的无序类型。我能想到的唯一解决方案是将这些列重新连接到旋转的 DF 中。所有相当昂贵的操作..
    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2018-05-13
    • 2022-11-22
    • 2021-12-03
    • 2022-08-04
    • 2021-04-08
    • 1970-01-01
    相关资源
    最近更新 更多