通过 hiveql 添加组 id
Add group id by hiveql
我在 hadoop 中有一个 table,它有 2 列包含字符串数据。
因此,对于看起来像这样的 table:
+---------+------+
| v1 | v2 |
+---------+------+
| 1 | 2 |
| 1 | 3 |
| 2 | 3 |
| 4 | 5 |
| 6 | 7 |
+---------+------+
现在,我想将组 ID 添加到每一行。无论值属于哪个列,具有相同值的行将获得相同的组 ID。
所以,像下面这样。
+---------+------+------+
| v1 | v2 | gid |
+---------+------+------+
| 1 | 2 | 1 |
| 1 | 3 | 1 |
| 2 | 3 | 1 |
| 4 | 5 | 2 |
| 6 | 7 | 3 |
+---------+------+------+
我怎样才能通过 hiveql 获取它?
一般来说,这是@GordonLinoff 所说的图遍历问题,但是如果任务可以减少到像您的示例中那样,具有有限的列和排序规则(我假设行的顺序由您的列定义), 这个任务是完全可以解决的。使用您的数据集查看此演示,它会产生所需的结果(阅读代码中的注释):
with your_data as ( --your data example
select stack (5,
1, 2,
1, 3,
2, 3,
4, 5,
6, 7
) as (v1,v2)
) --your data example
select v1, v2, --calculate group Id as a running count of new_grp
count(new_grp) over(order by v1, v2 rows between unbounded preceding and current row) as gid
from
(
select v1, v2, --calculate new_grp flag
case when ((not array_contains(prev_tuple,v1) and not array_contains(prev_tuple,v2)) or prev_tuple is null) then true end as new_grp
from
(
select v1, v2, lag(tuple) over (order by v1, v2) prev_tuple --get previous values in array, to simplify code a little bit
from (select v1, v2, array(v1, v2) as tuple from your_data) s
)s
)s;
结果:
v1 v2 gid
1 2 1
1 3 1
2 3 1
4 5 2
6 7 3
我在 hadoop 中有一个 table,它有 2 列包含字符串数据。
因此,对于看起来像这样的 table:
+---------+------+
| v1 | v2 |
+---------+------+
| 1 | 2 |
| 1 | 3 |
| 2 | 3 |
| 4 | 5 |
| 6 | 7 |
+---------+------+
现在,我想将组 ID 添加到每一行。无论值属于哪个列,具有相同值的行将获得相同的组 ID。
所以,像下面这样。
+---------+------+------+
| v1 | v2 | gid |
+---------+------+------+
| 1 | 2 | 1 |
| 1 | 3 | 1 |
| 2 | 3 | 1 |
| 4 | 5 | 2 |
| 6 | 7 | 3 |
+---------+------+------+
我怎样才能通过 hiveql 获取它?
一般来说,这是@GordonLinoff 所说的图遍历问题,但是如果任务可以减少到像您的示例中那样,具有有限的列和排序规则(我假设行的顺序由您的列定义), 这个任务是完全可以解决的。使用您的数据集查看此演示,它会产生所需的结果(阅读代码中的注释):
with your_data as ( --your data example
select stack (5,
1, 2,
1, 3,
2, 3,
4, 5,
6, 7
) as (v1,v2)
) --your data example
select v1, v2, --calculate group Id as a running count of new_grp
count(new_grp) over(order by v1, v2 rows between unbounded preceding and current row) as gid
from
(
select v1, v2, --calculate new_grp flag
case when ((not array_contains(prev_tuple,v1) and not array_contains(prev_tuple,v2)) or prev_tuple is null) then true end as new_grp
from
(
select v1, v2, lag(tuple) over (order by v1, v2) prev_tuple --get previous values in array, to simplify code a little bit
from (select v1, v2, array(v1, v2) as tuple from your_data) s
)s
)s;
结果:
v1 v2 gid
1 2 1
1 3 1
2 3 1
4 5 2
6 7 3