不幸的是,它不能一步到位。但是,它可以在两个步骤来实现: -
1)尽量插入数据有条件即如果键值已经存在不执行任何操作(即插入或更新 - 什么也没有发生)
2)如果有ConditionalCheckFailedException
,然后更新项目
示例代码: -
在下面的代码,usertable
是表名。该表的关键属性是userid
和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
)
更新: -
可变id
和密钥属性RequestId
的数据类型应该匹配。
你使用的是什么代码? – Kannaiyan
@Kannaiyan我编辑了这个问题。 – manojpt