gpt4 book ai didi

hadoop - HIVE如何根据某些条件更新现有数据,如果不存在则插入新数据

转载 作者:可可西里 更新时间:2023-11-01 15:49:00 28 4
gpt4 key购买 nike

如果现有数据存在,我想根据某些条件更新它(应该更新优先级更高的数据),如果不存在则插入新数据。

我已经为此编写了一个查询,但不知何故它重复了行数。以下是对我所拥有的以及我想要实现的目标的完整解释:

我有:表 1 - 列 - id、信息、优先级

hive> select * from sample1;
OK
1 123 1.01
2 234 1.02
3 213 1.03
5 213423 1.32
Time taken: 1.217 seconds, Fetched: 4 row(s)

表 2:列 - id、信息、优先级

hive> select * from sample2;
OK
1 1234 1.05
2 23412 1.01
3 21 1.05
4 1232 1.1
2 3432423 1.6
3 34324 1.4

我想要的是最终表的每个 id 应该只有 1 行,数据根据最高优先级排列:

1   1234    1.05
2 3432423 1.6
3 34324 1.4
4 1232 1.1
5 213423 1.32

我写的查询是这样的:

insert overwrite table sample1
select a.id,
case when cast(TRIM(a.prio) as double) > cast(TRIM(b.prio) as double) then a.info else b.info end as info,
case when cast(TRIM(a.prio) as double) > cast(TRIM(b.prio) as double) then a.prio else b.prio end as prio
from sample1 a
join
sample2 b
on a.id=b.id where b.id in (select distinct(id) from sample1)
union all
select * from sample2 where id not in (select distinct(id) from sample1)
union all
select * from sample1 where id not in (select distinct(id) from sample2);

运行此查询后,我得到以下结果:

hive> select * from sample1;
OK
1 1234 1.05
2 234 1.02
3 21 1.05
2 3432423 1.6
3 34324 1.4
5 213423 1.32
4 1232 1.1

如何修改当前查询以获得正确的结果。我是否可以遵循任何其他方法/过程来实现最终结果。我正在使用 hadoop 2.5.2 和 HIVE 1.2.1 。我在一个 6 节点集群上工作,该集群有 5 个从节点和 1 个 NN。

最佳答案

使用FULL JOIN,它将返回所有已连接的行加上来自左侧的所有未连接的行以及来自右表的所有未连接的行。sample2 表包含每个 id 的重复行,这就是连接重复行的原因,使用 row_number() 分析函数仅从中选择具有最高优先级的行示例 2 表:

insert overwrite table sample1
select
nvl(a.id, b.id) as id,
case when cast(TRIM(a.prio) as double) > cast(TRIM(b.prio) as double) then a.info else b.info end as info,
case when cast(TRIM(a.prio) as double) > cast(TRIM(b.prio) as double) then a.prio else b.prio end as prio
from ( select a.*, row_number() over (partition by id order by prio desc) rn
from sample1 a
) a
full join
( select b.*, row_number() over (partition by id order by prio desc) rn
from sample2 b
) b on a.id=b.id and b.rn=1 --join only with highest priority rows
where a.rn=1;

如果 sample1 表还包含每个 id 的多行(它不在您的示例中),请将使用 row_number 的相同技术应用于表 sample1。

另请参阅有关使用完全连接 进行合并的答案:https://stackoverflow.com/a/37744071/2700344

从 Hive 2.2 开始,您还可以使用 ACID Merge,请参阅 examples

关于hadoop - HIVE如何根据某些条件更新现有数据,如果不存在则插入新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53001909/

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