Unfortunately, this cannot be done in one step. However, this can be achieved in a two-step process: -
1) Try to insert data conditionally, that is, if the key value is already present, does not perform any operation (i.e., insert or update - nothing happens)
2) If there is a ConditionalCheckFailedException
, update the item
Code example:
The usertable
code usertable
the name of the table. The key attributes of the table are userid
and score
. You must accordingly modify the code below for your table structure.
In addition, I assigned a key value (like "Mike"). You must modify it accordingly for your use case.
from __future__ import print_function # Python 2/3 compatibility from boto.dynamodb2.exceptions import ConditionalCheckFailedException from botocore.exceptions import ClientError from boto3.dynamodb.conditions import Attr import boto3 import json import decimal # Helper class to convert a DynamoDB item to JSON. class DecimalEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, decimal.Decimal): if o % 1 > 0: return float(o) else: return int(o) return super(DecimalEncoder, self).default(o) dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000") table = dynamodb.Table('usertable') userId = "Mike" try : response = table.put_item( Item={ 'userid': userId, 'score' : 100, 'imagePath' : '/path/to/image' }, ConditionExpression=Attr('userid').ne(userId) ) print("Conditional PutItem succeeded:") print(json.dumps(response, indent=4, cls=DecimalEncoder)) except ClientError as ce : print("Conditional check failed:", ce) if ce.response['Error']['Code'] == 'ConditionalCheckFailedException': print("Key already exists") response = table.update_item( Key={'userid': userId, 'score' : 100}, UpdateExpression="set imagePath = :imagePathVal", ExpressionAttributeValues={":imagePathVal" : "/path/to/image" } ) print("Update existing item succeeded:") print(json.dumps(response, indent=4, cls=DecimalEncoder)) else: print("Unexpected error: %s" % e
)
Update: -
The data type of the variable id
and the key attribute RequestId
must match.
source share