我有一种情况找到具有parent_node_id层次结构表中的最低一级子节点如下child_node_id。源表是在蜂巢和Impala的数据库。请建议蜂巢/黑斑羚查询找出源表中的每一父节点的最低级别的子节点。
我试着用黑斑羚CTE递归查询,但我想这是不支持的。
先感谢您!
源表:
+-------------+--------------+
|child_node_id|parent_node_id|
+-------------+--------------+
| C1 | P1 |
+-------------+--------------+
| C2 | P2 |
+-------------+--------------+
| C11 | C1 |
+-------------+--------------+
| C12 | C11 |
+-------------+--------------+
| 123 | C12 |
+-------------+--------------+
预期输出:
+-------------+--------------+
|parent_node |lowest_l_child|
+-------------+--------------+
| P1 | 123 |
+-------------+--------------+
| P2 | C2 |
+-------------+--------------+
| C1 | 123 |
+-------------+--------------+
| C11 | 123 |
+-------------+--------------+
| C12 | 123 |
+-------------+--------------+
由于蜂巢不支持递归CTE查询。
请参阅[https://blog.pythian.com/recursion-in-hive/][1]一个选项。
其他选项是使用shell脚本中循环,并查询到所有的家长发现孩子最低。
以下步骤: - 1>初始化(一次运行)
create temporary table hier_temp as select * from Hier;
create table if not exists res as select * from hier where false;
2)查询找到最低水平的孩子
insert into table res
select
H1.parent, H1.Child
from hier_temp H1 left outer join hier_temp H2
on H1.Child=H2.Parent where H2.Child is null;
3)与孩子的一个新的水平覆盖临时表
insert overwrite table hier_temp
select
H1.Parent Parent, coalesce(H3.child, H2.child) as child
from hier_temp H1 left outer join hier_temp H2 on H1.Child=H2.Parent
left outer join res H3 on H2.child=H3.parent
where H2.Child is not null;
创建一个shell脚本将执行步骤2和3的序列中环(条件语句与突破,并继续将做的工作),直到我们没有在hier_temp表中的任何数据。
下面是从资源和hier_temp表给定的测试数据结果。
hive> select * from res;
OK
Time taken: 0.131 seconds
hive> select * from hier_temp;
OK
C1 C11
C11 C12
C12 123
P1 C1
P2 C2
Time taken: 0.108 seconds, Fetched: 5 row(s)
结果LOOP1后在步骤2和3中提到的查询
hive> select * from res;
OK
C12 123
P2 C2
Time taken: 0.137 seconds, Fetched: 2 row(s)
hive> select * from hier_temp;
OK
P1 C11
C1 123
C11 123
Time taken: 0.155 seconds, Fetched: 3 row(s)
结果循环2后,在步骤2和3中提到的查询
hive> select * from res;
OK
C12 123
P2 C2
C1 123
C11 123
Time taken: 0.11 seconds, Fetched: 4 row(s)
hive> select * from hier_temp;
OK
P1 123
Time taken: 0.111 seconds, Fetched: 1 row(s)
结果循环3进行查询,在步骤2和3中提及
hive> select * from res;
OK
P1 123
C12 123
P2 C2
C1 123
C11 123
Time taken: 0.115 seconds, Fetched: 5 row(s)
hive> select * from hier_temp;
OK
Time taken: 0.16 seconds
这将让你想要的结果,但你可能要考虑采取的执行时间。
希望这可以帮助