Amazon DynamoDB with Node.js

Learn how to use Amazon DynamoDB with Node.js

Introduction

Amazon Dynamo DB is a no-sql database service offered by Amazon. In this tutorial our objective is to briefly explain the core components of dynamo db after which we'll look at how to install dynamo db locally and perform crud operations using Node.js

Pre-requisites

To follow this tutorial, you need the following installed.

  1. Java 6 or higher needed to run dynamo db locally
  2. Nodejs 6 or higher

DynamoDB Core Components

In DynamoDB tables, items and attributes are the core components. We can relate these to tables, rows / records, attributes from our knowledge of traditional database systems. So just like many other database systems, tables are used to store collection of rows called items which are further composed of entities called attributes.

Install DynamoDB locally

We'll but using the local version of the DB in this tutorial instead of using the cloud based service. Just download the required package from the links below.
Download DynamoDB
In order to start DynamoDB, first extract the zip or tar file to a desired directory and then run the following command in that directory where you've extract the file DynamoDBLocal.jar

 
                         
java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb -port 3306
                         
                    

Note that -port 9999, by default dynamodb runs on port 8000, in case port 8000 is busy with some other process, you can specify some other port using the -port command.

Install aws sdk

 
                      
                      npm install aws-sdk 
                       
                   

In order to use the aws-sdk without any errors ensure that you've the credentials file in your ~/home/.aws directory [ for linux ] which stores the access credentials for your amazon user.

Now create a file called dynamotable.js and paste the following code into it. The following code basically configures and initializes the db object which we use to create a table. The params define the meta data for table. As we can see Attribute Name "year" is the Partition Key. [ Read comments for description of other attrubutes ]

 
                     
// amazon dynamo db create table using nodejs 
var AWS = require("aws-sdk");
AWS.config.update({
    region: "us-west-2",
    endpoint: "http://localhost:3306"   // 3306 is the port where we started our dynamo db 
});

var dynamodb = new AWS.DynamoDB();

var params = {  
    TableName: "Movies",        // name of the table 
    KeySchema: [
        { AttributeName: "year", KeyType: "HASH" }, //Partition key
        { AttributeName: "title", KeyType: "RANGE" } //Sort key
    ],
    AttributeDefinitions: [
        { AttributeName: "year", AttributeType: "N" },  // N stands for number
        { AttributeName: "title", AttributeType: "S" }  // S is a string 
    ],
    ProvisionedThroughput: {
        ReadCapacityUnits: 10,
        WriteCapacityUnits: 10
    }
};


dynamodb.createTable(params, function(err, data) {
    if (err) {
        console.error("Unable to create table. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("Created table. Table description JSON:", JSON.stringify(data, null, 2));
    }
});
     
    

Create Operation

Create operations is used add entries to the table. Create a file dynamo-create.js and paste the following code into it. It will create a new item in the movies table we created above.

 
 
// amazon dynamo db add entry to a table using node.js 
    var AWS = require("aws-sdk");

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

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": "Nothing happens at all.",
            "rating": 0
        }
    }
};

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));
    }
});

 

Read Operation

Now when we want to read the data from the table we created above, we use the read operation as follows. Just create a file dynamo-read.js and paste the following code into it to perform a read operations.

     
// amazon dynamo db read operation using node.js 
var AWS = require("aws-sdk");

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

var docClient = new AWS.DynamoDB.DocumentClient()

var table = "Movies";

var year = 2015;
var title = "The Big New Movie";

var params = {
    TableName: table,
    Key:{
        "year": year,
        "title": title
    }
};

docClient.get(params, function(err, data) {
    if (err) {
        console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
});

     

Update Operation

Updating records is again very similar to the operations we performed above except that in this case we have to give an Update Expression in order to tell what items to update. You can paste the following code into a file dynamo-update.js to see the update operations in action.

 
 
// amazon dynamo db update operation using node.js 
var AWS = require("aws-sdk");

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

var docClient = new AWS.DynamoDB.DocumentClient()

var table = "Movies";

var year = 2015;
var title = "The Big New Movie";

// Update the item, unconditionally,

var params = {
    TableName:table,
    Key:{
        "year": year,
        "title": title
    },
    UpdateExpression: "set info.rating = :r, info.plot=:p, info.actors=:a",
    ExpressionAttributeValues:{
        ":r":5.5,
        ":p":"Everything happens all at once.",
        ":a":["Larry", "Moe", "Curly"]
    },
    ReturnValues:"UPDATED_NEW"
};

console.log("Updating the item...");
docClient.update(params, function(err, data) {
    if (err) {
        console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));
    }
});


Delete Operation

Deleting can be performed using the delete method. To see it in action, copy the following code into a file dynamo-delete.js

 
     
// amazon dynamo db delete operation using node.js 
        var AWS = require("aws-sdk");

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

var docClient = new AWS.DynamoDB.DocumentClient();

var table = "Movies";

var year = 2015;
var title = "The Big New Movie";

var params = {
    TableName:table,
    Key:{
        "year":year,
        "title":title
    },
    ConditionExpression:"info.rating <= :val",
    ExpressionAttributeValues: {
        ":val": 5.0
    }
};

console.log("Attempting a conditional delete...");
docClient.delete(params, function(err, data) {
    if (err) {
        console.error("Unable to delete item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("DeleteItem succeeded:", JSON.stringify(data, null, 2));
    }
});

     

Love Code. Live Code.

RISHABH.iO