【问题标题】:Retrieve the struct from array of structs when struct field of struct type matches with specific value in spark scala当结构类型的结构字段与spark scala中的特定值匹配时,从结构数组中检索结构
【发布时间】:2021-05-23 16:59:23
【问题描述】:
Schema

root
|-- promotion-id: string (nullable = true)
|-- custom-attributes: struct (nullable = true)
|    |-- custom-attribute: array (nullable = true)
|    |    |-- element: struct (containsNull = true)
|    |    |    |-- value: string (nullable = true)
|    |    |    |-- attribute-id: string (nullable = true)


Sample Input Data 

promotion-id    custom-attributes.custom-attribute
100             [["x",1000],["y",2000]]
200             [["x",3000],["z",4000]]

Sample Output

promotion-id    col X   col Y   col Z
100             1000    2000    null
200             3000    null    4000

我正在使用 spark 2.3,并且我有一个具有以下架构的数据框

如果您注意到 custom-attributes.custom-attribute 是一个数组(结构)

现在我的属性 ID 为“x”。我需要检查数组内的任何结构中是否存在属性 ID "x" 并获取值输出。

我有一个属性 ID 和列名的列表

说 - 如果我的属性 ID 为“x”,则获取它的值并填充到 col X

下面是属性 ID 到列的映射 x -> col X , y -> col Y , z -> col Z

如果结构中没有可用的属性,则在该列中设置为 null

【问题讨论】:

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


    【解决方案1】:

    您可以inline 结构数组并对值进行透视。

    val df2 = df.selectExpr(
        "*", 
        "inline(`custom-attributes`.`custom-attribute`)"
    ).groupBy("promotion-id").pivot("value").agg(first(col("attribute-id")))
    
    df2.show
    +------------+----+----+----+
    |promotion-id|   x|   y|   z|
    +------------+----+----+----+
    |         100|1000|2000|null|
    |         200|3000|null|4000|
    +------------+----+----+----+
    

    注意使用反引号来转义列名中的连字符。一般来说,在列名中使用连字符不是一个好习惯,因为它们也可能意味着减去列。

    【讨论】:

    • 谢谢!我们可以在 pivot 中使用多个列吗?说对于 col X,如果不为空则选择结构字段 2,否则选择结构字段 3
    猜你喜欢
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    相关资源
    最近更新 更多