Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python3 dynamoDB Update_item do not work

I just practice using example code in AWS dynamoDB But, update code do not work with error

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

My python code is here. I could update DB without 'map' attribute.


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"
)
like image 454
Rawoon Kim Avatar asked May 15 '17 18:05

Rawoon Kim


1 Answers

This happens because you are trying to update nested properties of top level property info, which does not exist yet (OR is not of map type)

So before running this update you have to ensure that the top level attribute info already exists.

Or you can just catch the exception if it is thrown, and perform an another update creating the info attribute, like shown below:

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  
like image 97
xtx Avatar answered Oct 23 '22 20:10

xtx