python3 dynamoDB Update_item 不起作用

Raw*_*Kim 7 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
Run Code Online (Sandbox Code Playgroud)

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


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"
)
Run Code Online (Sandbox Code Playgroud)

xtx*_*xtx 10

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

因此,在运行此更新之前,您必须确保顶级属性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  
Run Code Online (Sandbox Code Playgroud)