如何更新DynamoDB中列表中的项目?

时间:2017-05-06 14:49:06

标签: amazon-dynamodb optimistic-locking

如何使用AWS SDK for C#更新项目?

让我们说我想更新"选择"值为" TRUE"当ItemName等于" eqq"。

我写了这段代码没有成功:

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);

DynamoDB表中的我的JSON数据遵循以下结构:

{
    "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"
}

1 个答案:

答案 0 :(得分:1)

您无法事先了解列表中的哪个项目将包含ItemName egg。您可以读取该项目,然后在具有ItemName = egg的Items列表中的第0项上进行条件。此策略需要您首先阅读该项目,以便您知道鸡蛋在列表中的位置。否则,您可以将项嵌套在地图中:

{
    "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"
}

并使用以下表达式:

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