更新添加dynamodb属性的项目
是否无法动态添加dynamodb属性?更新添加dynamodb属性的项目
当我尝试 - “提供的关键元素与模式不匹配时,我得到了此错误”。
方案 -
{ id : "123",
imageName : "elephant.jpg"
}
我要添加的属性 - 的ImagePath: “/路径/到/图像”,以上面的数据。 我使用了put_item,但它会替换旧的项目(如果存在)。
我正在寻找解决方案 - 如果id =“123”,然后添加imagePath属性,否则添加一个新的项目到表中。
使用put_item可以实现添加属性,但它会替换现有的项目。 我们如何使用update_item动态添加属性到现有数据?(将imagePath添加到给定的json)
我应该用imagePath更改表的模式,然后使用update_item函数吗?
我们如何使用python来实现这一点?
不幸的是,它不能一步到位。但是,它可以在两个步骤来实现: -
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
的数据类型应该匹配。
期望块仍然会给出错误“提供的关键元素与模式不匹配”,因为imagePath是我尝试添加的动态字段(imagePath不在表模式中)。这是什么解决方案? @notionquest – manojpt
Dynamodb接受动态字段。您不需要定义架构中的所有字段。在更新项目API中,您需要正确使用键属性。你的分区键和分类键是什么? – notionquest
您的分区键属性名称是RequestId还是Id? – notionquest
你使用的是什么代码? – Kannaiyan
@Kannaiyan我编辑了这个问题。 – manojpt