DynamoDB Update Multiple values

Viewed 998

I have the following table stored in DynamoDB:

{
    "name" :"A",
    "videos": [
        {
            "playlistId" : "ABCD"
            "title" : "Hello, world!"
        }
     ]
}

I want to make it into the following:

{
    "name" :"A",
    "videos": [
        {
            "playlistId" : "ABCD"
            "title" : "Hello, world!"
        },
        {
            "playlistId" : "EFGH"
            "title" : "Bye, world!"
        },
        {
            "playlistId" : "IJKL"
            "title" : "Good morning, world!"
        }
     ]
}

I tried to do it using DynamoDB Create operation, but it threw Duplicate Key error because all three video objects have the same primary key ("name").

Now, I am trying to do so by updating the "videos", by appending to the list. When I do so, it throws Unsupported type error. Can someone nudge me in the right direction in this?

1 Answers

You have to use UpdateExpression update_item boto3 API. Below is the code I tried to insert an item:

import boto3
ddb_session = boto3.resource('dynamodb', region_name='us-east-1')
table = ddb_session.Table('test_table')
table.put_item(Item={
    'name': 'A',
    'videos': [
        {
            "playlistId": "ABCD",
            "title": "Hello, world!"
    }
]})

To update Item A the below code can be used:

import boto3


ddb_session = boto3.resource('dynamodb', region_name='us-east-1')
table = ddb_session.Table('test_table')


table.update_item(
    Key={'name': 'A'},
    UpdateExpression='SET #VALUE = :value',
    ExpressionAttributeNames={
        '#VALUE': 'videos'
    },
    ExpressionAttributeValues={
        ':value': [
            {
                "playlistId": "ABCD",
                "title": "Hello, world!"
            },
            {
                "playlistId": "EFGH",
                "title": "Bye, world!"
            },
            {
                "playlistId": "IJKL",
                "title": "Good morning, world!"
            }
        ]
    },
)

Now let's see the output too. On put_item you will get something like below:

enter image description here

On calling update_item you would get something like:

enter image description here

that is what expected in question. You can read more about UpdateExpression here

Related