gpt4 book ai didi

amazon-web-services - 更新一个项目,在 dynamodb 中添加一个属性

转载 作者:行者123 更新时间:2023-12-04 03:03:41 25 4
gpt4 key购买 nike

难道不能在dynamodb中动态添加一个属性吗?

我在尝试时遇到此错误-“提供的关键元素与模式不匹配”。

场景-

{ id : "123",
imageName : "elephant.jpg"
}

我想为上述数据添加一个属性 - imagePath : "/path/to/image"。我使用了 put_item,但它会替换旧项目(如果存在的话)。

我正在寻找解决方案 - 如果 id = "123",则添加 imagePath 属性,否则将新项目添加到表中。

添加属性可以使用 put_item 来实现,但它会替换现有的项目。 我们如何使用 update_item 向现有数据动态添加属性?(将 imagePath 附加到给定的 json)

我是否应该使用 imagePath 更改表的架构,然后使用 update_item 函数?

我们如何使用 python 实现这一点?

最佳答案

不幸的是,它不能一步实现。但是,它可以通过两步过程实现:-

1) 尝试有条件地插入数据,即如果键值已经存在,则不执行任何操作(即插入或更新 - 什么都不会发生)

2) 如果出现ConditionalCheckFailedException,则更新项目

示例代码:-

在下面的代码中,usertable 是表名。该表的关键属性是useridscore。您需要根据您的表结构相应地更改以下代码。

此外,我还分配了键值(如“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的数据类型和key属性RequestId要匹配。

关于amazon-web-services - 更新一个项目,在 dynamodb 中添加一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46668886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com