不幸的是,它无法一步实现。但是,它可以通过两步过程来实现:-
1)尝试有条件地插入数据,即如果键值已经存在,则不执行任何操作(即插入或更新 - 什么也不会发生)
2)如果有一个ConditionalCheckFailedException
,然后更新该项目
示例代码:-
在下面的代码中,usertable
是表名。该表的关键属性是userid
and score
。您需要根据您的表结构相应地更改以下代码。
另外,我还分配了键值(如“Mike”)。您需要根据您的用例进行相应的更改。
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:-
变量的数据类型id
和关键属性RequestId
应该匹配。