如何使用 DICT 数据类型 (boto3) 更新 DynamoDB 表 [英] How to update DynamoDB table with DICT data type (boto3)

查看:18
本文介绍了如何使用 DICT 数据类型 (boto3) 更新 DynamoDB 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 DynamoDB 表,用于存储元数据,不同类型的数据具有不同的属性(文件大小、日期等,作为单独的属性).

I created a DynamoDB table that is used for storing metadata, with different attributes for different types of data (file size, date, etc., as separate attributes).

我正在尝试获取 Python3 字典并将其用作需要上传到表的一堆属性的来源.到目前为止,我已经能够成功地将整个字典作为一个属性上传,但我希望每个键:值对都成为数据库中自己的属性.换句话说,Python3 字典中的每个键:值对都应该在 DynamoDB 表中作为自己的键:值对结束.我知道我下面的代码到目前为止还没有设计成这样.

I am trying to take a Python3 dictionary and use it as the source for a bunch of attributes that need to be uploaded to the table. So far, I've been able to successfully upload the entire dictionary as one attribute, but I want each key:value pair to be its own attribute in the database. In other words, each key:value pair from the Python3 dictionary should end up as its own key:value pair in the DynamoDB table. I'm aware my code below is not designed to that so far.

这是我目前的代码:

file_attributes = dict(file.items())

    # Add all metadata to DynamoDB:
    response = table.update_item(
        UpdateExpression="set File_attributes = :f,"
        Key={
            'file_name': key,
        },
        ExpressionAttributeValues={
            ':f': file_attributes,

        },
        ReturnValues="UPDATED_NEW"
    )

推荐答案

我认为您正在寻找以下方面的东西:

I think you are looking for something along these lines:

update_expression = 'SET {}'.format(','.join(f'#{k}=:{k}' for k in file))
expression_attribute_values = {f':{k}': v for k, v in file.items()}
expression_attribute_names = {f'#{k}': k for k in file}

response = table.update_item(
    Key={
        'file_name': key,
    },
    UpdateExpression=update_expression,
    ExpressionAttributeValues=expression_attribute_values,
    ExpressionAttributeNames=expression_attribute_names,
    ReturnValues='UPDATED_NEW',
)

我修改了您的示例以使用 ExpressionAttributeValues 和 ExpressionAttributeNames 动态生成更新表达式.需要使用名称别名,因为我们不知道 file 字典中的项目名称是什么.生成的更新表达式将包含 file 字典中每个顶级键的 set 语句.属性名称以 # 符号为前缀,属性值以 : 符号为前缀.

I modified your example to generate update expression dynamically using both ExpressionAttributeValues and ExpressionAttributeNames. Usage of name aliases was required, because we do not know what are the names of the items inside file dictionary. Generated update expression will contain set statement for each top-level key inside file dictionary. Attribute names are prefixed with # sign, and attribute values are prefixed with : sign.

这篇关于如何使用 DICT 数据类型 (boto3) 更新 DynamoDB 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆