简体   繁体   English

如何更新 map DynamoDB 中的属性

[英]How to update attributes in map DynamoDB

I want to update attributes #name in #info but sometimes #info doesn't exist我想更新 #info 中的属性 #name 但有时 #info 不存在

table.update_item(
    Key={
        'id': '001'
    },
    UpdateExpression='SET #k = if_not_exists(#k, :i), #k.#ks = :kv',
    ExpressionAttributeNames={
        '#k': 'info',
        '#ks': 'name'
    },
    ExpressionAttributeValues={
        ':i': {},
        ':kv': 'new_name'
    }
)

An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression: Two document paths overlap with each other;调用 UpdateItem 操作时发生错误(ValidationException):Invalid UpdateExpression:两个文档路径相互重叠; must remove or rewrite one of these paths;必须删除或重写这些路径之一; path one: [info], path two: [info, name]路径一:[信息],路径二:[信息,名称]

I want to check if #info exists.我想检查 #info 是否存在。 If not, create a new #info, if there is, update #name.如果没有,创建一个新的#info,如果有,更新#name。

Shortly: try to update the field assuming it exists, in case of failure, check that you got a validation exception due to the non existing field you are trying to update, and create it from the root level.很快:尝试更新该字段,假设它存在,如果失败,请检查是否由于您尝试更新的字段不存在而导致验证异常,并从根级别创建它。

Otherwise, set the info field as an empty dict at entry creation time.否则,在条目创建时将info字段设置为空字典。

def udpateItemName(id, val):
    try:
        table.update_item(
            Key={
                'id': id
            },
            UpdateExpression='SET #k.#ks = :kv',
            ExpressionAttributeNames={
                '#k': 'info',
                '#ks': 'name',
            },
            ExpressionAttributeValues={
                ':kv': val
            }
        )
    }
    except botocore.exceptions.ClientError as ce:
        if ce.response['Error']['Code'] != 'ValidationException':
            # some further checks can be made on ['Error']['Message'] here to be sure 
            # that the error is due to non existing path
            raise ce
        table.update_item(
            Key={
                'id': id
            },
            UpdateExpression='SET #k = :kv',
            ExpressionAttributeNames={
                '#k': 'info'
            },
            ExpressionAttributeValues={
                ':kv': {"name": val}
            }
        )
    }   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM