gpt4 book ai didi

python3 dynamoDB Update_item 不工作

转载 作者:太空宇宙 更新时间:2023-11-03 14:54:04 25 4
gpt4 key购买 nike

我只是在 AWS dynamoDB 中练习使用示例代码但是,更新代码不会出错

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the UpdateItem operation: The document path provided in the update expression is invalid for update

我的 python 代码在这里。我可以在没有“ map ”属性的情况下更新数据库。


table = dynamodb.Table('Movies')

title = "The Big New Movie"
year = 2015

response = table.update_item(
Key={
"year": year,
"title": title
},
UpdateExpression="set #attrName.rating = :r, #attrName.plot=:p",
ExpressionAttributeNames = {
"#attrName" : "info"
},
ExpressionAttributeValues={
':r': decimal.Decimal(5.5),
':p': "Everything happens all at once."
},
ReturnValues="UPDATED_NEW"
)

最佳答案

发生这种情况是因为您正在尝试更新顶级属性 info 的嵌套属性,该属性尚不存在(或者不属于 map type)

因此,在运行此更新之前,您必须确保顶级属性 info 已经存在。

或者您可以在抛出异常时捕获异常,然后执行另一个更新来创建 info 属性,如下所示:

from botocore.exceptions import ClientError

table = dynamodb.Table('Movies')

title = "The Big New Movie"
year = 2015

try:
# Adding new nested attributes `rating` and `plot`
# if the top field `info` already exists and is a map
response = table.update_item(
Key={
"year": year,
"title": title
},
UpdateExpression="set #attrName.rating = :r, #attrName.plot=:p",
ExpressionAttributeNames = {
"#attrName" : "info"
},
ExpressionAttributeValues={
':r': decimal.Decimal(5.5),
':p': "Everything happens all at once."
},
ReturnValues="UPDATED_NEW"
)

except ClientError as e:
if e.response['Error']['Code'] == 'ValidationException':
# Creating new top level attribute `info` (with nested props)
# if the previous query failed
response = table.update_item(
Key={
"year": year,
"title": title
},
UpdateExpression="set #attrName = :attrValue",
ExpressionAttributeNames = {
"#attrName" : "info"
},
ExpressionAttributeValues={
':attrValue': {
'rating': decimal.Decimal(5.5),
'plot': "Everything happens all at once."
}
},
ReturnValues="UPDATED_NEW"
)
else:
raise

关于python3 dynamoDB Update_item 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43986643/

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