夏期劇場
夏期劇場

Reputation: 18347

DynamoDB: How to append values into the List (Array) of an existing Item

(I'm using AWS PHP SDK)

Let's say i have a Table:

Table name: article
Primary partition key: article_id (Number)

With a sample of manually created Item:

{
    "article_id": 10010,
    "updated": "2018-02-22T20:15:19.28800Z",
    "comments": [ "Nice article!", "Thank you!" ]
}

Adding new comment:

I know how to entirely update (overwrite) this existing Item, in this way:

$key = $marshaler->marshalJson('
    {
        "article_id": 10010
    }
');

$eav = $marshaler->marshalJson('
    {
        ":u": "2018-02-22T20:15:19.28800Z",
        ":c": [ "Nice article!", "Thank you!", "This is the new one!" ]
    }
');

$params = [
    'TableName' => 'article',
    'Key' => $key,
    'ExpressionAttributeValues'=> $eav,
    'UpdateExpression' => 'set updated=:u, comments=:c',
    'ReturnValues' => 'UPDATED_NEW'
];

I can somehow APPEND new values (aka) add new comment, this way. But this is literally still recreating the whole entire Item again, which is not the way i preferred.

How do i just simply APPEND new values into an List/Array inside an existing Item, please?

Upvotes: 1

Views: 3544

Answers (1)

Andi
Andi

Reputation: 394

Add elements to the list

When you use SET to update a list element, the contents of that element are replaced with the new data that you specify. If the element does not already exist, SET will append the new element at the end of the list.

Create Table

aws dynamodb create-table \
    --table-name article \
    --attribute-definitions AttributeName=article_id,AttributeType=N \
    --key-schema AttributeName=article_id,KeyType=HASH \
    --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1

Add item

aws dynamodb put-item  \
        --table-name article \
        --item '{
            "article_id": {"N": "123"},
            "updated": {"S": "00:00:00"},
            "comments": {
                  "L": [
                    { "S": "Nice article!" },
                    { "S": "Thank you!" }
                ]}
          }'

Update Item

aws dynamodb update-item \
    --table-name article \
    --key '{"article_id":{"N":"123"}}' \
    --update-expression "SET comments[50] = :c, updated=:u" \
    --expression-attribute-values '{
        ":u": {"S": "01:01:01"},
        ":c": {"S": "This is the new one!"}
      }' \
    --return-values ALL_NEW

List comments[] contain two elements (index 0 and 1) before the update. As comments[50] doesn't exist, the SET operation will append it to the end of the list (comments[2]).

Upvotes: 1

Related Questions