python3 dynamoDB Update_item不起作用

Rawoon金

我只是练习在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"
)
xtx

发生这种情况是因为您尝试更新顶级属性的嵌套属性info,而该属性尚不存在(或不是地图类型

因此,在运行此更新之前,您必须确保顶级属性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  

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章