从数据块中的数组列中获取数据而无需交叉连接 [英] Get data from array columns in databricks without cross joining

查看:15
本文介绍了从数据块中的数组列中获取数据而无需交叉连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一张桌子:

<头>
idarray_col
101[{系统":x",值":1"},{系统":y",值":2"},{";系统":z",值":3"}]

其中 array_col 基本上包含一个结构数组

Where array_col basically contains an array of structures

0:{系统":x",值":1"}

0: {"system": "x", "value": "1"}

1:{系统":y",值":2"}

1: {"system": "y", "value": "2"}

2:{系统":z",值":3"}

2: {"system": "z", "value": "3"}

我需要如下表的输出:

<头>
id系统价值
101x1
101y2
101z3

现在我正在尝试在子查询中使用爆炸(因为不能在单个选择语句中有多个爆炸,然后根据 id 加入它们.但这给了我一个输出,其中每个系统都显示为每个值,所以我得到 9 个结果而不是 3 个.

Right now I'm trying to use explode in sub queries (Since can't have multiple explode in a single select statement, and then joining them based on id. But that is giving me an output where each system is showing for each value, so instead of 3 i'm getting 9 results.

<头>
id系统价值
101x1
101x2
101x3
101y1
101y2
101y3
101z1
101z2
101z3

帮助我获得 3 行而不是 9 行的输出.

Help me get the output with 3 rows, instead of 9.

推荐答案

Try inline:

df.selectExpr('id', 'inline(array_col)').show()
+---+------+-----+
| id|system|value|
+---+------+-----+
|101|     x|    1|
|101|     y|    2|
|101|     z|    3|
+---+------+-----+

以上假设数组包含结构,而不是作为字符串的结构.如果你的结构是字符串,你需要先用 from_json 解析它们:

The above assumes that the arrays contains structs, not structs as strings. If your structs are strings, you need to parse them with from_json first:

df2 = df.selectExpr(
    'id', 'explode(array_col) array_col'
).selectExpr(
    'id', "inline(array(from_json(array_col, 'struct<system:string, value:string>')))"
)

df2.show()
+---+------+-----+
| id|system|value|
+---+------+-----+
|101|     x|    1|
|101|     y|    2|
|101|     z|    3|
+---+------+-----+

这篇关于从数据块中的数组列中获取数据而无需交叉连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆