python3 dynamoDB Update_item不起作用

时间:2017-05-15 18:41:33

标签: python python-3.x amazon-dynamodb boto3

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

1 个答案:

答案 0 :(得分:1)

这是因为您尝试更新顶级属性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