Hive 如何遍历配置单元中以逗号分隔的列?
我有一个配置单元外部表data_table(id bigint,dataset string),其中dataset是一组逗号分隔的整数或字符串值,如Hive 如何遍历配置单元中以逗号分隔的列?,hive,hiveql,Hive,Hiveql,我有一个配置单元外部表data_table(id bigint,dataset string),其中dataset是一组逗号分隔的整数或字符串值,如 id dataset 1 4,3,0,6 2 1,9,7 3 0,8,2,7 我的问题:如何使用配置单元迭代逗号分隔的数据集值 假设当id=2(因此数据集=1,9,7)时,我希望有一个循环结构,允许我创建如下内容: when id=2, select val from source where x=1; select va
id dataset
1 4,3,0,6
2 1,9,7
3 0,8,2,7
我的问题:如何使用配置单元迭代逗号分隔的数据集值
假设当id=2(因此数据集=1,9,7)时,我希望有一个循环结构,允许我创建如下内容:
when id=2,
select val from source where x=1;
select val from source where x=9;
select val from source where x=7;
有什么建议吗
SELECT id, dummy.x FROM baseTable
LATERAL VIEW explode(split(dataset,'\\,') dummy AS x;
将为您提供如下表格:
id x
1 4
1 3
1 0
1 6
2 1
2 9
2 7
3 0
3 8
3 7
3 2
SELECT id, explodeTable.dataset from data_table LATERAL VIEW explode(split(dataset,'\\,')) testTable as explodeTable
现在您可以:
select id, x
from newtable
where x in (1,9,7)
您需要在
上拆分数据集
,
和分解
select id, x
from (
select id, split(dataset, '\\,') dataset_array
from table ) A
lateral view explode(dataset_array) explodetable as x
不太确定之后要做什么,但我将让您编写此查询的外层。在理想情况下,您不应该有需要在数据集上迭代的用例。 如果您只需要访问一个特定的元素,那么只需使用方括号操作符和类似于myArray[index]的索引即可 在其他情况下,hive中的explode()函数(如上所述)应该对您的情况有所帮助。语法:
SELECT id, explodeTable.dataset from data_table LATERAL VIEW explode(dataset) testTable as explodeTable
确保分割数据集以从中获取数组。您可以使用split函数来实现这一点。语法:
split(dataset,'\\,')
您的最终查询应如下所示:
id x
1 4
1 3
1 0
1 6
2 1
2 9
2 7
3 0
3 8
3 7
3 2
SELECT id, explodeTable.dataset from data_table LATERAL VIEW explode(split(dataset,'\\,')) testTable as explodeTable
Explode函数只接受数组或映射作为参数。当我尝试使用类似的函数时,我获取失败:ClassCastException org.apache.hadoop.hive.serde2.objectinspector.StandardListObjectInspector无法强制转换为org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector尝试
拆分数组时会出现此异常。您确定数据集
的类型为字符串
,而不是数组
?如果数据集
是一个数组
,比如[0,4,3,6]
,那么只需分解(数据集)
,如果它是一个字符串
,你需要拆分字符串
,使其成为数组。就像Gobrewer14回答一样,当我尝试实现类似的东西时,我得到一个失败:ClassCastException org.apache.hadoop.hive.serde2.objectinspector.StandardListObjectInspector不能强制转换为org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector。我做了一个可能有帮助的小更改,但看到GoBrewers注释并测试列数据集是否为string类型@阿吉特