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,我有一个具有以下模式的数据帧
如果您注意到customAttributes.custom-attribute是一个数组(结构(
现在我的属性ID为";x〃;。我需要检查属性ID";x〃;存在于数组内的任何结构中,并获取值输出。
我有一个属性ID和列名的列表
比如-如果我有一个属性ID为";x〃;获取它的值并填充到col X 中
以下是属性ID到列的映射x->列X、y->col Y、z->col Z
如果结构中没有可用的属性,那么只需在列中设置为null
您可以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|
+------------+----+----+----+
请注意使用反勾号来转义列名中的连字符。通常,在列名中使用连字符不是一个好的做法,因为它们也可能意味着要减去列。