不幸的是,它不能一步到位。但是,它可以在兩個步驟來實現: -
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