Burc Hasergin
Burc Hasergin

Reputation: 519

How to update an item in a list in DynamoDB?

How can I update the items with AWS SDK for C#?

Lets say i want to update the "Selected" value to "TRUE" when ItemName equals "eqq".

I wrote this code without success:

request = {
    ExpressionAttributeNames = new Dictionary<string, string>()
    {
        {"#I", "Items"},
        {"#lN", item.ItemName}
    },
    ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
    {
        { ":item", new AttributeValue
            { L = new List<AttributeValue> {
                { new AttributeValue
                    { M = new Dictionary<string,AttributeValue> {
                        { "ListName", new AttributeValue { S =  "item.ItemName"} },
                        { "Selected", new AttributeValue { BOOL =  item.Selected} },
                        { "ImageSource", new AttributeValue { S =  item.ImageSource} }
                    }}
                }
            }}
        }
    },
    UpdateExpression = "SET #I.#lN = :item"
    // UpdateExpression = "SET #I = list_append(:item,#I )"
    // UpdateExpression = "SET #I = :item"
};
var response = await client.UpdateItemAsync(request);

My JSON data in the DynamoDB table follows the structure below:

{
    "Items": [
        {
            "ImageSource": "checked.png",
            "ItemName": "egg",
            "Selected": true
        },
        {
            "ImageSource": "checked.png",
            "ItemName": "Water",
            "Selected": true
        }
    ],
    "ListCategory": "Technology",
    "ListCreator": "John",
    "ListId": "e5a7ec9d-b00c-41f3-958a-84c8c183d702",
    "ListName": "Test5",
    "UpdateDateTıme": "2017-05-05T21:48:41.833Z"
}

Upvotes: 1

Views: 2419

Answers (1)

Alexander Patrikalakis
Alexander Patrikalakis

Reputation: 5205

You can't know a priori which item in the list will contain the ItemName egg. You could read the item and then condition on the 0th item in the Items list having an ItemName=egg. This strategy would require you to read the item first, so that you know what position the egg is in the list. Otherwise, you could nest the items in a map:

{
    "ItemMap": {
        "egg":{
            "ImageSource": "checked.png",
            "Selected": true
        },
        "Water": {
            "ImageSource": "checked.png",
            "Selected": true
        }
    },
    "ListCategory": "Technology",
    "ListCreator": "John",
    "ListId": "e5a7ec9d-b00c-41f3-958a-84c8c183d702",
    "ListName": "Test5",
    "UpdateDateTıme": "2017-05-05T21:48:41.833Z"
}

and use the following expressions:

  1. UpdateExpression = ItemMap.egg.Selected = :bv
  2. ExpressionAttributeValues = {:bv: true}
  3. ConditionExpression = attribute_exists(ItemMap.egg) AND attribute_type(ItemMap.egg, M)

Upvotes: 1

Related Questions