munna_1
munna_1

Reputation: 131

How to updateItem for Map dataType in dynamoDB

I am trying to use Map datatype in dynamodb to insert my JSON object. The JSON I am getting from external API is bit long and got nested Array of objects in it. (I am using nodejs.)

{
    "a": "foo",
    "b": "foo1",
    "c": [{
        "boo": 10,
        "boo1": 15
    }, {
        "boo": 19,
        "boo1": 45
    }, {
        "boo": 11,
        "boo1": 25
    }]
}

From the research i made so far it looks like i have to specify types for every single element in the json i am trying to insert/update. It make it harder since in my case the json could have anything.

If anyone experienced the same issue and know any solution for it please let me know.

Upvotes: 2

Views: 3515

Answers (2)

Borys Serebrov
Borys Serebrov

Reputation: 16172

You need to specify the exact types for every value only if you use the low-level AmazonDB API.

But you can use an AWS SDK which makes things much easier and you can use the json notation directly.

I didn't use node.js SDK (have experience with python SDK), but looking at the examples, this is true for node.js too.

Check this one:

var AWS = require("aws-sdk");

AWS.config.update({
  region: "us-west-2",
  endpoint: "http://localhost:8000"
});

var docClient = new AWS.DynamoDB.DocumentClient();    
var table = "Movies";    
var year = 2015;
var title = "The Big New Movie";

var params = {
    TableName:table,
    Item:{
        "year": year,
        "title": title,
        "info":{
            "plot":"Something happens."
        }
    }
};

console.log("Adding a new item...");
docClient.put(params, function(err, data) {
    if (err) {
        console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("Added item:", JSON.stringify(data, null, 2));
    }
});

Here the Item inside the params passed into the docClient.put call is just a plain javascript object.

Upvotes: 2

Poorna Anu
Poorna Anu

Reputation: 13

It's necessary for dynamodb to know what type of data your are inserting/updating. So dynamodb or any db allows only datatype that is specific to that column. If you looking to parse json(with Jackson api) to specific type and insert. Below is the code

    JsonParser parser = new JsonFactory().createParser(new File(
            "target/resources/json_file.json"));
    JsonNode rootNode = new ObjectMapper().readTree(parser);
    Iterator<JsonNode> iter = rootNode.iterator();
    ObjectNode currentNode;
    while (iter.hasNext()) {
        currentNode = (ObjectNode) iter.next();
        table.putItem(new Item().withPrimaryKey("a", currentNode.path("a").asText(), "b",
          currentNode.path("b").asText()).withJSON("c",currentNode.path("c").toString()));
    }

Upvotes: 1

Related Questions