AWS Glue 到 Redshift:是否可以替换、更新或删除数据?

AWS Glue to Redshift: Is it possible to replace, update or delete data?

以下是关于我如何设置的一些要点:

通过重新运行 作业,我在 redshift 中得到了重复的行(正如预期的那样)。但是,有没有办法在插入新数据之前使用键或胶水中的分区设置来替换或删除行?

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

from awsglue.dynamicframe import DynamicFrame
from awsglue.transforms import SelectFields

from pyspark.sql.functions import lit

## @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)

columnMapping = [
    ("id", "int", "id", "int"),
    ("name", "string", "name", "string"),
]

datasource1 = glueContext.create_dynamic_frame.from_catalog(database = "db01", table_name = "table01", transformation_ctx = "datasource0")

applymapping1 = ApplyMapping.apply(frame = datasource1, mappings = columnMapping, transformation_ctx = "applymapping1")
resolvechoice1 = ResolveChoice.apply(frame = applymapping1, choice = "make_cols", transformation_ctx = "resolvechoice1")
dropnullfields1 = DropNullFields.apply(frame = resolvechoice1, transformation_ctx = "dropnullfields1")
df1 = dropnullfields1.toDF()
data1 = df1.withColumn('platform', lit('test'))
data1 = DynamicFrame.fromDF(data1, glueContext, "data_tmp1")

## Write data to redshift
datasink1 = glueContext.write_dynamic_frame.from_jdbc_conf(frame = data1, catalog_connection = "Test Connection", connection_options = {"dbtable": "table01", "database": "db01"}, redshift_tmp_dir = args["TempDir"], transformation_ctx = "datasink1")

job.commit()

工作书签是关键。只需编辑作业并启用 "Job bookmarks",它就不会处理已处理的数据。 请注意,作业必须重新运行一次才能检测到它不必再次重新处理旧数据。

有关详细信息,请参阅: http://docs.aws.amazon.com/glue/latest/dg/monitor-continuations.html

"bookmark"这个名字在我看来有点牵强。如果不是在搜索过程中偶然发现它,我永远不会看它。

这是我从 AWS Glue Support 获得的解决方案:

如您所知,虽然您可以创建主键,但 Redshift 并不强制要求唯一性。因此,如果您重新运行 Glue 作业,则可能会插入重复的行。保持唯一性的一些方法是:

  1. 使用分段 table 插入所有行,然后在主 table 中执行 upsert/merge [1],这必须在胶.

  2. 在您的 redshift table [1] 中添加另一列,例如插入时间戳,以允许重复但要知道哪个先出现或最后出现,然后删除重复项,如果您需要。

  3. 将之前插入的数据加载到dataframe中,然后比较要插入的数据,避免重复插入[3]

[1] - http://docs.aws.amazon.com/redshift/latest/dg/c_best-practices-upsert.html and http://www.silota.com/blog/amazon-redshift-upsert-support-staging-table-replace-rows/

[2] - https://github.com/databricks/spark-redshift/issues/238

[3] - https://kb.databricks.com/data/join-two-dataframes-duplicated-columns.html

Glue 中的作业书签选项应该可以达到上面的建议。当我的源是 S3 时,我一直在成功使用它。 http://docs.aws.amazon.com/glue/latest/dg/monitor-continuations.html

根据我的测试(使用相同的场景),BOOKMARK 功能不起作用。当作业 运行 多次时,将插入重复数据。我通过每天(通过 lambda)从 S3 位置删除文件并实施暂存和目标表来解决此问题。数据将根据匹配的键列得到 insert/update。

今天我已经测试并找到了使用 JDBC 连接从目标 table 到 update/delete 的解决方法。

我用过如下

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

import pg8000
args = getResolvedOptions(sys.argv, [
    'JOB_NAME',
    'PW',
    'HOST',
    'USER',
    'DB'
])
# ...
# Create Spark & Glue context

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

# ...
config_port = ****
conn = pg8000.connect(
    database=args['DB'], 
    user=args['USER'], 
    password=args['PW'],
    host=args['HOST'],
    port=config_port
)
query = "UPDATE table .....;"

cur = conn.cursor()
cur.execute(query)
conn.commit()
cur.close()



query1 = "DELETE  AAA FROM  AAA A, BBB B WHERE  A.id = B.id"

cur1 = conn.cursor()
cur1.execute(query1)
conn.commit()
cur1.close()
conn.close()

请检查this答案。有解释和代码示例如何使用暂存 table 将数据更新到 Redshift。同样的方法可以用于 运行 Glue 使用 preactionspostactions 选项写入数据之前或之后的任何 SQL 查询:

// Write data to staging table in Redshift
glueContext.getJDBCSink(
  catalogConnection = "redshift-glue-connections-test",
  options = JsonOptions(Map(
    "database" -> "conndb",
    "dbtable" -> staging,
    "overwrite" -> "true",
    "preactions" -> "<another SQL queries>",
    "postactions" -> "<some SQL queries>"
  )),
  redshiftTmpDir = tempDir,
  transformationContext = "redshift-output"
).writeDynamicFrame(datasetDf)