合并为更新/插入



我在databricks笔记本中与大量数据集合并时遇到问题。如何将merge into脚本转换为update/insert

target_table = f"""
MERGE INTO {target_table_name} target
USING {staging_table_name} source
ON
source.ResponseRgBasketId = target.ResponseRgBasketId
AND source.RequestTimestamp   = target.RequestTimestamp
WHEN
MATCHED
THEN UPDATE SET
*
WHEN NOT MATCHED
THEN INSERT
*

对于来自仅通过MERGE支持的另一个表的事务表UPDATE。请参阅:https://community.cloudera.com/t5/Support-Questions/update-one-hive-table-based-on-another-table/td-p/160017

因此,您可以在ACID模式中使用相同的MERGE,但不使用仅用于UPDATE的WHEN NOT MATCHED。对于非ACID,只使用不存在或左联接执行INSERT操作,如下面的INSERT only示例(同样适用于ACID(。

使用非ACID表可以单独执行这些操作,但也可以使用INSERT OVERWRITE+LEFT JOIN代替UPDATE。

您可以创建非ACID表,并使用左联接来重写它(整个表(,但在这种情况下,将插入和更新分开不会给您带来任何有用的东西,因为这两个操作都需要联接。

仅更新:

create table new_target_table --if table exists, use INSERT OVERWRITE table new_target_table 
as 
select col1, ... colN,
coalesce (s.col, t.col) as col
...
from target_table_name t 
left join source s
on s.ResponseRgBasketId = t.ResponseRgBasketId
and s.RequestTimestamp   = t.RequestTimestamp

仅插入:

insert into new_target_table 
select from source s 
left join target t 
on s.ResponseRgBasketId = t.ResponseRgBasketId
and s.RequestTimestamp   = t.RequestTimestamp
where t.ResponseRgBasketId is null --If target does not exists

一起插入和更新(与ACID模式下的合并相同(:

insert overwrite table new_target_table 
select case when s.ResponseRgBasketId is null then t.col else s.col end   as col,
case when s.ResponseRgBasketId is null then t.col2 else s.col2 end as col2
...
from source s 
FULL JOIN target t 
on s.ResponseRgBasketId = t.ResponseRgBasketId
and s.RequestTimestamp   = t.RequestTimestamp