简体   繁体   中英

How to add to a 'Map of Maps' in DynamoDB with boto3 (python)

I have the following structure in DynamoDB:

{
  "fruits": {
    "1": {
      "identifier": "orange",
      "colour": "orange"
    },
    "2": {
      "identifier": "strawberry",
      "colour": "red"
    }
  },
  "username": "my-username"
}

How do I add a '3rd fruit item' with its associated attributes? I am aiming to achieve the following:

{
  "fruits": {
    "1": {
      "identifier": "orange",
      "colour": "orange"
    },
    "2": {
      "identifier": "strawberry",
      "colour": "red"
    },
    "3": {
      "identifier": "pear",
      "colour": "green"
    }
  },
  "username": "my-username"
}

I have tried something similar to the following:

result = table.update_item(
    Key={
        'username': str('my-username')
    },
    UpdateExpression='set fruits.3.identifier = :i, fruits.3.colour = :c',
    ExpressionAttributeValues={
        ':i': 'pear',
        ':c': 'green'
    }
)

Thank you!

You cannot directly set attributes such as fruits.3.identifier because fruits.3 does not exist yet. Instead, you must set fruits.3 as a whole object.

Your update expression should be something like this:

result = table.update_item(
    Key={
        'username': str('my-username')
    },
    UpdateExpression='set fruits.3 = :newFruit',
    ExpressionAttributeValues={
        ':newFruit': {
            'colour': 'green',
            'identifier': 'pear'
        }
    }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM