gpt4 book ai didi

python - 如何使用 AWS Glue 在 dynamodb 中编写字符串集?

转载 作者:行者123 更新时间:2023-12-04 03:40:20 26 4
gpt4 key购买 nike

我需要将数据从一个发电机表复制到另一个,并在此过程中进行一些转换。为此,我将数据从源表导出到 s3 并在其上运行爬虫。
在我的胶水作业中,我使用以下代码:

mapped = apply_mapping.ApplyMapping.apply(
frame=source_df,
mappings=[
("item.uuid.S", "string", "uuid", "string"),
("item.options.SS", "set", "options", "set"),
("item.updatedAt.S", "string", "updatedAt", "string"),
("item.createdAt.S", "string", "createdAt", "string")
],
transformation_ctx='mapped'
)
df = mapped.toDF() //convert to spark df
// apply some transformation
target_df = DynamicFrame.fromDF(df, glue_context, 'target_df') //convert to dynamic frame
glue_context.write_dynamic_frame_from_options(
frame=target_df,
connection_type="dynamodb",
connection_options={
"dynamodb.region": "eu-west-1",
"dynamodb.output.tableName": "my-table",
"dynamodb.throughput.write.percent": "1.0"
}
)
在源发电机表中 options字段是一个字符串集。在转型中,它保持不变。但是,目标表中有一个字符串列表:
"options": {
"L": [
{
"S": "option A"
},
{
"S": "option B"
}
]
}
谁能建议如何使用 AWS Glue 将字符串集写入 DynamoDB?

最佳答案

不幸的是,我找不到使用 Glue 接口(interface)将字符串集写入 DynamoDB 的方法。我找到了一些使用 boto3 和 Spark 的解决方案,所以这是我的解决方案。我跳过了转换部分并总体上简化了示例。

# Load source data from catalog
source_dyf = glue_context.create_dynamic_frame_from_catalog(
GLUE_DB, GLUE_TABLE, transformation_ctx="source"
)

# Map dynamo attributes
mapped_dyf = ApplyMapping.apply(
frame=source_dyf,
mappings=[
("item.uuid.S", "string", "uuid", "string"),
("item.options.SS", "set", "options", "set"),
("item.updatedAt.S", "string", "updatedAt", "string"),
("item.updatedAt.S", "string", "createdAt", "string")
],
transformation_ctx='mapped'
)


def _putitem(items):
resource = boto3.resource("dynamodb")
table = resource.Table("new_table")
with table.batch_writer() as batch_writer:
for item in items:
batch_writer.put_item(Item=item)


df = mapped_dyf.toDF()
# Apply spark transformations ...

# save partitions to dynamo
df.rdd.mapPartitions(_putitem).collect()
取决于您的数据量,您可能希望增加 boto3 中的重试次数,甚至更改 mechanism .
此外,您可能想要使用 DynamoDB 配置。我切换到按需运行此特定迁移,但有 catch

关于python - 如何使用 AWS Glue 在 dynamodb 中编写字符串集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66163027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com