胶水创建重复记录,如何解决?

Glue creates duplicates of records, how to fix it?

目前,我们使用 Glue(python 脚本)将数据从 MySQL 数据库迁移到 RedShift 数据库。 昨天,我们发现了一个问题:一些记录是重复的,这些记录在 MySQL 数据库中使用相同的主键。根据我们的要求,RedShift数据库中的所有数据应该与MySQL数据库中的数据相同。

我试图在迁移前删除 RedShift table,但没有找到相应的方法...

你能帮我解决这个问题吗?

import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job

## @params: [TempDir, JOB_NAME]
args = getResolvedOptions(sys.argv, ['TempDir','JOB_NAME'])

sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)

datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "glue-db", table_name = "table", transformation_ctx = "datasource0")
applymapping0_1 = ApplyMapping.apply(frame = datasource0, mappings = [...], transformation_ctx = "applymapping0_1")
resolvechoice0_2 = ResolveChoice.apply(frame = applymapping0_1, choice = "make_cols", transformation_ctx = "resolvechoice0_2")
dropnullfields0_3 = DropNullFields.apply(frame = resolvechoice0_2, transformation_ctx = "dropnullfields0_3")
datasink0_4 = glueContext.write_dynamic_frame.from_jdbc_conf(frame = dropnullfields0_3, catalog_connection = "redshift-cluster", connection_options = {"dbtable": "table", "database": "database"}, redshift_tmp_dir = args["TempDir"], transformation_ctx = "datasink0_4")

我的解决办法是:

datasink0_4 = glueContext.write_dynamic_frame.from_jdbc_conf(frame = dropnullfields0_3, catalog_connection = "redshift-cluster", connection_options = {"dbtable": "mytable", "database": "mydatabase", "preactions": "delete from public.mytable;"}

Redshift 不施加唯一键约束

除非你能保证你的源脚本避免重复,否则你需要运行一个常规的工作来在 redshift 上删除重复,

delete from yourtable
where id in
(
select id
from yourtable
group by 1
having count(*) >1
)
;

您是否认为 DMS 可以替代 Glue?这可能更适合你。

如果您的目标不是在目标 table 中有重复项,您可以对 JBDC 接收器使用 postactions 选项(参见 this answer for more details). Basically it allows to implement Redshift merge 使用暂存 table。

对于你的情况应该是这样的(替换现有记录):

post_actions = (
         "DELETE FROM dest_table USING staging_table AS S WHERE dest_table.id = S.id;"
         "INSERT INTO dest_table (id,name) SELECT id,name FROM staging_table;"
         "DROP TABLE IF EXISTS staging_table"
    )
datasink0_4 = glueContext.write_dynamic_frame.from_jdbc_conf(frame = dropnullfields0_3, catalog_connection = "redshift-cluster", connection_options = {"dbtable": "staging_table", "database": "database", "overwrite" -> "true", "postactions" -> post_actions}, redshift_tmp_dir = args["TempDir"], transformation_ctx = "datasink0_4")