How to update an item in Dynamodb of type String Set (SS)?

谁都会走 提交于 2021-02-06 15:49:36

问题


I have created a attribute of type String Set. When I create the Item and assign an attribute of type SS everything works. But when I try to update this attribute, the data type changes to a list ("L").

I try this:

qw = new AWS.DynamoDB.DocumentClient();

var params = {
  TableName : "myTable",
  Key: {
    "id": somekey
  },
  UpdateExpression: "set ssvar= :arrp",
  ExpressionAttributeValues: {
     ":arrp": [ "test", "test2" ]
  }
};

qw.update (etc.)

This leads to a change in datatype in dynamodb and in stead of a string set I get a list:

"ssvar": {
            "L": [
                {
                    "S": "test"
                }, 
                {
                    "S": "test2"
                }
            ]
        }

I have tried all kinds of solutions like below but always my datatype gets changed.

  ExpressionAttributeValues: {
     ":arrp": 
        "SS": [ "test", "test2" ]
  }

How can I update an attribute of type string set?


回答1:


This is an artifact of using the DocumentClient - StringSet is not a JSON type.

The DocumentClient converts a StringSet to the Array native JavaScript type: https://github.com/aws/aws-sdk-js/blob/master/lib/dynamodb/converter.js#L61. Then the client serializes the native JavaScript Array as a DynamoDB List type: https://github.com/aws/aws-sdk-js/blob/master/lib/dynamodb/converter.js#L12.

If you want to use the StringSet type, you can use the low-level API: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html




回答2:


As of September 2015, there is a createSet function in the DocumentClient that you can use for this.

UPDATE - added example

I've modified your example code to use this function:

qw = new AWS.DynamoDB.DocumentClient();

var params = {
  TableName : "myTable",
  Key: {
    "id": somekey
  },
  UpdateExpression: "set ssvar= :arrp",
  ExpressionAttributeValues: {
     ":arrp": qw.createSet([ "test", "test2" ])
  }
};

qw.update (etc.)



回答3:


An alternative simpler syntax

Upsert Item and Add "A" to set

const documentClient = new AWS.DynamoDB.DocumentClient();
await documentClient.update({
    TableName,
    Key: { hashKey, sortKey },
    AttributeUpdates: {
      'userIDs': {
        Action: 'ADD',
        Value: documentClient.createSet(['A' ])
      },
    },
  }).promise();

Upsert Item and remove "A" from set

await documentClient.update({
    TableName,
    Key: { hashKey, sortKey },
    AttributeUpdates: {
      'userIDs': {
        Action: 'DELTE',
        Value: documentClient.createSet(['A'])
      },
    },
  }).promise();
  • Update expression docs
  • documentClient.createSet
  • documentClient.update


来源:https://stackoverflow.com/questions/37194794/how-to-update-an-item-in-dynamodb-of-type-string-set-ss

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!