AWS Lambda: How to Add Numbers to a NS Set in Dynamodb

How to Create a Set and Add Items to a Set

let AWS = require('aws-sdk');
let docClient = new AWS.DynamoDB.DocumentClient();

...

var params = {
    TableName : 'Hex',
    Key: {'hex': '#FEFEFE'},
    UpdateExpression : 'ADD #oldIds :newIds',
    ExpressionAttributeNames : {
      '#oldIds' : 'ids'
    },
    ExpressionAttributeValues : {
      ':newIds' : docClient.createSet([1,2])
    }
};

docClient.update(params, callback);

Which results in this dynamodb table:

using the

If the set doesn't exist, then that code will create it for you. You can also run that code with a different set to update the set's elements. Super convenient.

Create a Set and Add Items to a Set (OLD API)

let doc = require('dynamodb-doc');
let dynamo = new doc.DynamoDB();

var params = {
    TableName : 'Hex',
    Key: {'hex': '#555555'},
    UpdateExpression : 'ADD #oldIds :newIds',
    ExpressionAttributeNames : {
      '#oldIds' : 'ids'
    },
    ExpressionAttributeValues : {
      ':newIds' : dynamo.Set([2,3], 'N')
    }
};

dynamo.updateItem(params, callback);

(Don't use this code for future development, I only include it to help anyone using the existing DynamoDB Document SDK)

Why the Original Was Failing

Notice how when I asked the question, the resulting set looked like a literal json map object (when viewed in the dynamodb screenshot), which would explain this error message

"errorMessage": "Invalid UpdateExpression: Incorrect operand type for operator or function; operator: ADD, operand type: MAP"

So I was using the wrong syntax. The solution is found in the (now depricated) AWS Labs dynamodb-document-js-sdk docs

The full documentation for the newer Document Client can be viewed here: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html


I've been struggling with this too. I discovered that there are actually 2 api's for DynamoDB.

AWS.DynamoDB

AWS.DynamoDBDocumentClient

Like you, I was not able to make the ADD function work. I tried to import and use the DynamoDB api instead of the DynamoDBDocumentClient api. It solved the problem for me. Below is my code snippet that works with the DynamoDB api but not with the DynamoDBDocumentClient api. I use a String Set instead of a Number Set, but that won’t make a difference I guess.

var AWS = require('aws-sdk');
var dynamo = new AWS.DynamoDB();
// var dynamo = new AWS.DynamoDB.DocumentClient();

...

var params = {};
params.TableName = “MyTable”;
params.ExpressionAttributeValues = { ':newIds': { "SS": ["someId"] } };
// :newIds represents a new dynamodb set with 1 element
params.UpdateExpression = "ADD someAttribute :newIds";
dynamoClient.updateItem(params, function(err, data) { ….}