gpt4 book ai didi

hive - 如何在 Hive 中分解具有未知数组长度的嵌套结构数组?

转载 作者:行者123 更新时间:2023-12-04 17:57:00 46 4
gpt4 key购买 nike

我有一个配置单元表 emp_test,如下所示:

'name' as string <br>
'testing' as array< struct < code:string,tests:array < struct < testtype:string,errorline:string>>>>

并具有列值:“name”为“JOHN”,“testing”为

[{"code":"cod1234","tests":[{"testtype":"java","errorline":"100"},{"testtype":"C++","errorline":"10000"}]},<br>
{"code":"cod6790","tests":[{"testtype":"hive","errorline":"10"},{"testtype":"pig","errorline":"978"},{"testtype":"spark","errorline":"35"}]}
]

如何选择这些值并存储在另一个表中

emp_test_detail(name,code,testtype,errorline) as

JOHN cod1234 java 100 <br>
JOHN cod1234 C++ 10000<br>
JOHN cod6790 hive 10<br>
JOHN cod6790 pig 978<br>
JOHN cod6790 spark 35<br>

我尝试了下面的查询但得到了错误:

*insert into emp_test_detail select <br>
emp_tasting.code, <br>
emp_tasting.emp_tests.testtype, <br>
emp_tasting.emp_tests.errorline from emp_test <br>
lateral view explode(testing) mytest as emp_tasting <br>
lateral view explode(testing[0].tests) mytest as emp_tasting;* <br>

这里我不知道测试数组的确切长度,那么如何引用数组字段呢?

请帮我解决这个问题?

最佳答案

在您的示例查询中,错误可能与使用 emp_tasting 有关,lateral view explode 行的列别名相同。他们需要有不同的别名。

要取消嵌套两层深的数组,您需要分解第一个数组,然后在分解嵌套数组时引用该分解数组的别名。

例如,你想要name, code, testtype, errorline

name直接在表格中可用
代码从第一次爆炸开始可用
testtypeerrorline 可从嵌套爆炸中获得。

请注意,我正在查看您的架构,而不是您列出的数据,这对我来说更容易推理

这个查询应该做你想做的

SELECT
name,
testingelement.code,
test.testtype,
test.errorline
FROM emp_test
LATERAL VIEW explode(testing) testingarray as testingelement
LATERAL VIEW explode(testingelement.tests) testsarray as test;

表和列的别名

请注意,explode 后面添加了两个别名,第一个用于它生成的表表达式,第二个用于列。

所以在这个例子中

横向 View 将(测试)测试数组分解为测试元素

testingarray 是表的别名
testingelementarray 列别名,您需要引用它来提取结构中的字段。

跳过第一次爆炸

如果您只想要直接来自表和嵌套数组的字段,那么您可以通过执行单个 LATERAL VIEW 分解来简化该查询

LATERAL VIEW explode(testing.tests) 测试数组作为测试

这样做的问题是它也会爆炸空数组,你不能使用 * 星展开,你必须明确地引用字段名称。这不是坏事。

不好的事情是必须在查询中使用数组索引。一旦您开始编写 field[0],就会有一些奇怪的味道。那只会获得数组的第一个元素,正如您所说,它依赖于事先知道数组的大小,这将有非常有限的用例。

关于hive - 如何在 Hive 中分解具有未知数组长度的嵌套结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39699422/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com