DynamoDB: how to add values ​​to a list in a document

I have a DynamoDB table, users, which has a document structure similar to the following:

{ "id": "1", "name": "john", "hobbies": [ { "description": "painting", "skill": "amateur" }, { "description": "cooking", "skill": "expert" } ] } 

As you can see, the document structure contains an attribute of the list, a hobby, which may contain a collection of "objects" for a hobby.

I want to write an update statement to add a new element to the list attribute, if it does not already exist.

For example, I want to be able to transfer a hobby with a "description" of "design" and the "skill" of an "amateur" to my update function and, since this hobby is not yet included in the list of hobbies, it should be added to the list. If a hobby already exists, it cannot be added a second time.

I work in Node.js and therefore use JavaScript and AWS.DynamoDB.DocumentClient () with a parameter map to perform my functions. The AWS documentation was helpful, but I'm struggling to find examples of how to configure options for conditionally adding items to a list attribute, as I have descriptions. Does anyone possibly have some tips on how to do this?

+5
source share
1 answer

You can use list_append() and if_not_exists() together in UpdateExpression to add to a potentially nonexistent column in the list, but there is no way to prevent this list from being added if an object with the same properties already exists inside the list.

Alternatively, you can replace your "hobby" list with a set of lines and the entire JSON.stringify() each "hobbie" before inserting it (and JSON.parse() when reading the values):

 var AWS = require('aws-sdk') var DB = new AWS.DynamoDB.DocumentClient() var hobbieToAdd = JSON.stringify({ description: "designing", skill: "amateur" }) DB.update({ TableName: "TableName", Key: { id: "1" }, UpdateExpression: "ADD #hobbies :hobbie", ExpressionAttributeNames: { "#hobbies" : "hobbies" }, ExpressionAttributeValues: { ":hobbie": DB.createSet([hobbieToAdd]) } }) 

Using a rowset ensures that duplicates never appear, but also require (de) serializing the hobby on its own.

+2
source

Source: https://habr.com/ru/post/1263258/


All Articles