首页 > 解决方案 > ETL过程中数据库中重复记录的问题

问题描述

我目前的ETL架构如下:

s3 --> staging table --> python dataframe --> destination table
  1. 来自 s3 的记录被加载到临时表中
  2. Python脚本连接到临时表
  3. Python 脚本每隔一小时运行一次以进行一些复杂的转换
  4. 来自 python 的结果数据帧被上传到目标表中

但是,我遇到了目标表中重复记录的问题:

| Time | New records (S3) | Redshift staging table (postgre) | Python DataFrame | Redshift Destination Table (postgre) | Duplicate records |
|------|------------------|----------------------------------|------------------|--------------------------------------|-------------------|
| 9am  | 3 records        | 3 records                        | 3 records        | 3 records                            | 0 (3-3)           |
| 10am | 2 records        | 5 (3+2) records                  | 5 records        | 8 (3+5) records                      | 3 (8-5)           |
| 11am | 4 records        | 9 (5+4) records                  | 9 records        | 17 (9+8) records                     | 8 (17-9)          |

所以在上午 11 点,临时表有 9 条记录,但目标表有 17 条记录(上午 11 点目标表中共有 8 条重复记录)

如何确保目标表中的总记录与暂存表中的记录匹配

(我无法消除临时表。现在,我正在过滤目标表以仅选择唯一记录。有没有更好的方法来做到这一点?)

标签: pythonpostgresqlamazon-s3amazon-redshiftetl

解决方案


您的阶段和目标表都在 Postgres 中,因此只需编写逻辑,将阶段表中的数据与目标表中的数据进行比较,并从阶段中删除目标表中已存在的任何记录。

DELETE FROM staging
WHERE EXISTS(SELECT 1 FROM dest WHERE dest.id = staging.id);

https://www.postgresql.org/docs/8.1/static/functions-subquery.html


推荐阅读