【问题标题】:How to add an attribute to the dynamoDB table item if it does not exist and add value to that attribute?如果 dynamoDB 表项不存在,如何为其添加属性并向该属性添加值?
【发布时间】:2021-02-11 01:23:57
【问题描述】:

我正在尝试为 dynamoDB 表中类型为 LIST 的属性“dataname”添加值。

        response = table.update_item(
            Key={"name": xyz},
            UpdateExpression="SET dataname = list_append(dataname, :i)"
            ExpressionAttributeValues={
                ':i': [1200, readonly],
            },
        )

仅当属性“dataname”已存在于项目中时,上述逻辑才有效。 如果该属性不存在,则会给出以下错误:“提供的表达式引用了项目中不存在的属性”。

如果项目中不存在属性“dataname”,有没有办法添加它然后更新值? 我正在为此使用 Python 语言。

【问题讨论】:

    标签: python-3.x amazon-web-services amazon-dynamodb


    【解决方案1】:

    我最近使用了这样的实现:

    import boto3
    
    update_expression = "SET #dataname = list_append(if_not_exists(#dataname, :empty_list), :i)"
    
    dynamodb = boto3.resource("dynamodb")
    result_table = dynamodb.Table(TABLE_NAME)
    
    result_table.update_item(
        Key={
            "name": "xyz",
        },
        UpdateExpression=update_expression,
        ExpressionAttributeNames={
            "#dataname": "dataname",
        },
        ExpressionAttributeValues={
            ":empty_list": [],
            ":i": [1200, readonly],
    )
    
    

    这改编自我在 Nasreen Ustad 在stackoverflow 上找到的 NodeJS 实现)并翻译成 Python。 (Looks like there is a sort of canonical answer for this without the complete implementation)

    它基本上是这样工作的:

    1. 它检查#dataname 属性是否存在,如果是则使用它,否则将使用:empty_list 的值来代替它
    2. 然后新值将附加到列表中。

    【讨论】:

    • 谢谢。这完全符合我的要求。 @莫里斯
    • 出于好奇,假设属性“dataname”是一个MAP,是否仍然可以这样做?猜猜 list_append 不会工作。 @莫里斯
    • 如果 list_appends 适用于地图,我会感到惊讶,您可能是对的。 Here 是设置嵌套地图属性的示例,您也可以在那里使用if_not_exists 技术 - 只需添加一个空地图而不是空列表;-)
    猜你喜欢
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多