Hive查询基于多个可选键分配分组键

问题描述 投票:1回答:1

我们有一个带有三个不同ID的Hive表,都是可选的。在每行中,必须提供三个ID中的至少一个。如果提供了多个ID,则会在多个ID之间建立等效。

我们需要根据在任何行中建立的等价来为每一行分配唯一的主ID。例如:

Line   id1     id2     id3    masterID
--------------------------------------
(1)    A1                     M1
(2)            A2             M1
(3)                    A3     M1
(4)    A1      A2             M1
(5)            A2      A3     M1
(6)    B1      A2             M1
(7)    C1              C3     M2

因为在第4行,A1和A2都存在,我们知道这些ID是等价的。

同样,在第5行,A2和A3都存在,我们知道这些ID也是等价的。

再次在第6行,我们有B1和A2,所以这些也是等价的。

在第7行,我们在C1和C3之间有一个等价。

鉴于上述信息,A1,A2,A3和B1都是等价的。因此,必须为包含任何这些ID的所有行分配相同的主ID,因此我们为它们提供了所有相同的主ID(“M1”)。第7行接收一个唯一的ID(“M2”),因为它的ID都不匹配任何其他ID。

我们如何编写Hive查询以这种方式分配主ID?如果Hive不是实现这一目标的最佳工具,您是否可以建议使用Hadoop生态系统中的其他工具为这些行分配主ID?

hadoop hive mapreduce hadoop2
1个回答
1
投票

您可以通过将ID表示为顶点并查找连接的组件来解决此问题。更多关于here的想法,第3.5节。让init_table是你的桌子。首先,构建一个链接表

create table links as
select distinct id1 as v1, id2 as v2
  from init_table
 where id1 is not null and id2 is not null
union all 
select distinct id1 as v1, id3 as v2
  from init_table
 where id1 is not null and id3 is not null
union all 
select distinct id2 as v1, id3 as v2
  from init_table
 where id2 is not null and id3 is not null
;

接下来为每个链接生成一些数字,例如行号并执行传播:

create table links1 as
with temp_table as (
  select v1, v2, row_number() over () as score
    from links
)
, tbl1 as (
  select v1, v2, score
       , max(score) over (partition by v1) as max_1
       , max(score) over (partition by v2) as max_2
    from temp_table
)
select v1, v2, greatest(max_1, max_2) as unique_id
  from tbl1
; 

然后只需将ID与匹配表联系起来:

create table matching_table as
with temp_table as (
select v1 as id, unique_id
  from link1
union all
select v2 as id, unique_id
  from link1
)
select distinct id, unique_id
  from temp_table

如果某些ID没有耦合,那么找出哪些ID并不难。希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.