2

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 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic answer. Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.