Example of update_item in dynamodb boto3

后端 未结 5 776
陌清茗
陌清茗 2020-12-14 00:10

Following the documentation, I\'m trying to create an update statement that will update or add if not exists only one attribute in a dynamodb table.

I\'m trying this

5条回答
  •  情深已故
    2020-12-14 00:52

    The original code example:

    response = table.update_item(
        Key={'ReleaseNumber': '1.0.179'},
        UpdateExpression='SET',
        ConditionExpression='Attr(\'ReleaseNumber\').eq(\'1.0.179\')',
        ExpressionAttributeNames={'attr1': 'val1'},
        ExpressionAttributeValues={'val1': 'false'}
    )
    

    Fixed:

    response = table.update_item(
        Key={'ReleaseNumber': '1.0.179'},
        UpdateExpression='SET #attr1 = :val1',
        ConditionExpression=Attr('ReleaseNumber').eq('1.0.179'),
        ExpressionAttributeNames={'#attr1': 'val1'},
        ExpressionAttributeValues={':val1': 'false'}
    )
    

    In the marked answer it was also revealed that there is a Range Key so that should also be included in the Key. The update_item method must seek to the exact record to be updated, there's no batch updates, and you can't update a range of values filtered to a condition to get to a single record. The ConditionExpression is there to be useful to make updates idempotent; i.e. don't update the value if it is already that value. It's not like a sql where clause.

    Regarding the specific error seen.

    ExpressionAttributeNames is a list of key placeholders for use in the UpdateExpression, useful if the key is a reserved word.

    From the docs, "An expression attribute name must begin with a #, and be followed by one or more alphanumeric characters". The error is because the code hasn't used an ExpressionAttributeName that starts with a # and also not used it in the UpdateExpression.

    ExpressionAttributeValues are placeholders for the values you want to update to, and they must start with :

提交回复
热议问题