brandonknewman
brandonknewman

Reputation: 11

Adding multiple key:value pairs to DynamoDB to existing map?

Let's say I have an item in the test table in DynamoDB like this:

test: {
    {
        id:'100',
        page:'#test',
        general: {
            foo: 'super_foo',
            bar: {
                    item:'string_item'
                }
        }
    }
}

I'd like to find a way to make it end up like:

test: {
    {
        id:'100',
        page:'#test',
        general: {
            foo: 'super_foo',
            bar: {
                item:'string_item'
                },
            bbb: { 'bbbb':'cccc' },
            ccc: 'dddd'
        }
    }
}

I tried the following (in python, using boto3):

table.update_item(
        Key = {
            'id': '100',
            'page': 'page_name'
        },
        UpdateExpression= "set #g=:r",
        ExpressionAttributeValues={
            ':r': { 'bbb': { 'bbbb':'cccc' }, 'ccc': 'dddd' },
        },
        ExpressionAttributeNames = {
            '#g': 'general'
        },
)

...but it only erased the items I already had:

test: {
    {
        id:'100',
        page:'#test',
        general: {
            bbb: { 'bbbb':'cccc' },
            ccc: 'dddd'
        }
    }
}

Is this possible to do?

Upvotes: 1

Views: 1382

Answers (1)

jarmod
jarmod

Reputation: 78860

Please try the following:

table.update_item(
    Key={
        'id': '100',
        'page': '#test'
    },
    UpdateExpression="SET #general.#bbb = :bbb, #general.#ccc = :ccc",
    ExpressionAttributeValues={':bbb': {'bbbb':'cccc'}, ':ccc': 'dddd'},
    ExpressionAttributeNames={'#general':'general', '#bbb':'bbb', '#ccc':'ccc'}
)

Note that DynamoDB interprets a dot in an expression attribute name as a character within the attribute's name (as opposed to a separator between levels of a hierarchical attribute's name), so you can't simply set an ExpressionAttributeNames value of general.bbb. Instead, you need to define an expression attribute name for each element in the document path (so general and bbb independently).

Upvotes: 2

Related Questions