3

I am trying to append to a string set (array of strings) column, which may or may not already exist, in a DynamoDB table. I referred to SO questions like this and this when writing my UpdateExpression.

My code looks like this.

const AWS = require('aws-sdk')
const dynamo = new AWS.DynamoDB.DocumentClient()

const updateParams = {
    // The table definitely exists.
    TableName: process.env.DYNAMO_TABLE_NAME,
    Key: {
      email: user.email
    },
    // The column may or may not exist, which is why I am combining list_append with if_not_exists.
    UpdateExpression: 'SET #column = list_append(if_not_exists(#column, :empty_list), :vals)',
    ExpressionAttributeNames: {
      '#column': 'items'
    },
    ExpressionAttributeValues: {
      ':vals': ['test', 'test2'],
      ':empty_list': []
    },
    ReturnValues: 'UPDATED_NEW'
}

dynamo.update(updateParams).promise().catch((error) => {
    console.log(`Error: ${error}`)
})

However, I am getting this error: ValidationException: An operand in the update expression has an incorrect data type. What am I doing incorrectly here?


[Update] Thanks to Nadav Har'El's answer, I was able to make it work by amending the params to use the ADD operation instead of SET.

const updateParams = {
    TableName: process.env.DYNAMO_TABLE_NAME,
    Key: {
      email: user.email
    },
    UpdateExpression: 'ADD items :vals',
    ExpressionAttributeValues: {
      ':vals': dynamo.createSet(['test', 'test2'])
    }
}

1 Answer 1

2

A list and a string set are not the same type - a string set can only hold strings while a list may hold any types (including nested lists and objects), element types don't need to be the same, and a list can hold also duplicate items. So if your original item is indeed as you said a string set, not a list, this explains why this operation cannot work.

To add items to a string set, use the ADD operation, not the SET operation. The parameter you will give to add should be a set (not a list, I don't know the magic js syntax to specify this, check your docs) with a bunch of elements. If the attribute already exists these elements will be added to it (dropping duplicates), and if the attribute doesn't already exit, it will be set to the set of these elements. See the documentation here: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateItem.html#DDB-UpdateItem-request-UpdateExpression

1
  • 1
    You're right, the issue was that I was using a SET operation on a string set column. Using ADD worked. Thank you! Commented Mar 2, 2020 at 23:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.