Home > Back-end >  Update a dynamodb item only if it already exists
Update a dynamodb item only if it already exists

Time:07-15

I'm trying to update an item on a dynamodb, however i don't want it to create a new item if it doesnt exist. I've tried:

dynamodb = boto3.client('dynamodb')
element = 'test'
dynamodb.update_item(
               TableName='myTable',
               Key={
                   'serial':{
                       'S':element
                   }
               },
               AttributeUpdates={
                   'total':{
                       'Value':{
                           'N':'0'
                       },
                       'Action':'PUT'
                   }
               },
              UpdateExpression ='serial= :serial',
              ExpressionAttributeNames={
               ':serial':'VM1'
              }
           ) 

But i get this error:

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the UpdateItem operation: Can not use both expression and non-expression parameters in the same request: Non-expression parameters: {AttributeUpdates} Expression parameters: {UpdateExpression}

CodePudding user response:

You would want to use a conditional expression if you want to update an item based on certain criteria. In your case it would be something like this:

dynamodb = boto3.client('dynamodb')
element = 'VM1'
try:
    dynamodb.update_item(
        TableName='myTable',
        Key={
            'serial': {
                'S': element
            }
        },
        UpdateExpression='SET tot = :val', # total is reserved word, you cannot use it
        ExpressionAttributeValues={
            ':val': {
                'N': '0'
            }
        },
        ConditionExpression='attribute_exists(serial)' # update only if the item exists in the database
    )
except ClientError as e:
    # if the item does not exist, we will get a ConditionalCheckFailedException, which we need to handle
    if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
        print(e.response)
  • Related