UpdateExpression to flatten the record

Viewed 138

I have such items in Dynamo DB:

[{
  "Id": "1",
  "Data": {
    "Value": "test"
  }
},
{
  "Id": "2",
  "Data": {}
},
{
  "Id": "3"
},
{
  "Id": "4",
  "Data": {
    "Wrong": "234"
  }
}]

And I'm trying to make it flatten, but for the Data.Value field only:

[{
  "Id": "1",
  "Value": "test"
},
{
  "Id": "2"
},
{
  "Id": "3"
},
{
  "Id": "4"
}]

My Update request looks like this:

var request = new UpdateItemRequest {
    TableName = "<table>",
    Key = new Dictionary<string, AttributeValue> {{"Id", new AttributeValue("<item-id>")}},
    UpdateExpression = "SET #a = #c.#a REMOVE #c",
    ExpressionAttributeNames = new Dictionary<string, string> {
        {"#c", "Data"},
        {"#a", "Value"}
    }
};

This works well for Id = 1 and 3. But does not work for 2 and 4. I assume because it can not do a SET. It does not throw any errors, but simply does not delete the Data attribute.

Is there a way to make it in a single call?

1 Answers

you just need a condition with your expression, to check if the attribute exist or not, thats it.

    ConditionExpression ="attribute_exists (#c.#a)"
    

For more détails in Amazon doncs here.

Related