簡體   English   中英

僅當 dynamodb 項目已存在時才更新它

[英]Update a dynamodb item only if it already exists

我正在嘗試更新 dynamodb 上的項目,但是如果它不存在,我不希望它創建一個新項目。 我試過了:

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'
              }
           ) 

但我得到這個錯誤:

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}

如果要根據特定條件更新項目,則可能需要使用條件表達式 在你的情況下,它會是這樣的:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM