ETL过程中数据库中出现重复记录的问题

2024-06-17 10:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我当前的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条重复记录)

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

(我无法删除暂存表。现在,我正在筛选目标表以只选择唯一的记录。有更好的方法吗?)你知道吗


Tags: 脚本目标redshiftdataframes3体系结构记录table
1条回答
网友
1楼 · 发布于 2024-06-17 10:28:38

stage和destination表都在Postgres中,所以只需编写逻辑,将stage表中的数据与dest表中的数据进行比较,并从stage中删除dest表中已经存在的所有记录。你知道吗

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

相关问题 更多 >