Create DynamoDB Table Locally

2020/12/304 min read
bookmark this
Responsive image

AWS DynamoDB is one of the AWS services for the NoSQL database on the cloud. You can create an AWS account then go to the AWS console's DynamoDB section to create a table and add items. On the SQL database, you or someone need to create a server for the SQL database, you then access the SQL database on that server by SQL query, but on the other hand, AWS will be managing the server for this NoSQL, serverless DynamoDB database. You can access it by the HTTP request.

What about the local environment!? On the SQL side, you can set up the SQL database on your local, how about the DynamoDB? You can reference this blog for how to setup Dynamodb in your local environment. This blog will show how to create a DynamoDB table in your local environment.

The following example code was using Node.js running on Mac OS. npm version is 6.12.0, node version is v12.13.0.

Following code snippet assume you already set up local DynamoDB and is running by this.

Create a DynamoDB table - node.js

Following code will require npm package aws-sdk to access DynamoDB by node.js.

var AWS = require("aws-sdk");
function createTable() {
    AWS.config.update({
        region: "us-west-2",
        endpoint: "http://localhost:8000"
    });
      
    var dynamodb = new AWS.DynamoDB();
    var params = {
        TableName : 'MyFakeFriend',
        KeySchema: [        
            { AttributeName: "name", KeyType: "HASH" },
            { AttributeName: "age", KeyType: "RANGE" },
        ],
        AttributeDefinitions: [       
            { AttributeName: "name", AttributeType: "S" },
            { AttributeName: "age", AttributeType: "S" }
        ],
        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));
        }
    });  
}
createTable();

Save above code somewhere on your local environment, assume you save as app.js, cd to the folder directory then run command as following.

node app.js

If no error shows, you should be see following message from the response.

Created table. Table description JSON: {
  "TableDescription": {
    "AttributeDefinitions": [
      {
        "AttributeName": "name",
        "AttributeType": "S"
      },
      {
        "AttributeName": "age",
        "AttributeType": "S"
      }
    ],
    "TableName": "MyFakeFriend",
    "KeySchema": [
      {
        "AttributeName": "name",
        "KeyType": "HASH"
      },
      {
        "AttributeName": "age",
        "KeyType": "RANGE"
      }
    ],
    "TableStatus": "ACTIVE",
    "CreationDateTime": "...",
    "ProvisionedThroughput": {
      "LastIncreaseDateTime": "1970-01-01T00:00:00.000Z",
      "LastDecreaseDateTime": "1970-01-01T00:00:00.000Z",
      "NumberOfDecreasesToday": 0,
      "ReadCapacityUnits": 10,
      "WriteCapacityUnits": 10
    },
    "TableSizeBytes": 0,
    "ItemCount": 0,
    "TableArn": "arn:aws:dynamodb:ddblocal:000000000000:table/MyFakeFriend"
  }
}

In the above example, I'm trying to create a DynamoDB table called MyFakeFriend, and set the name as the partition key, age as the sort key. One thing good for setup DynamoDB locally is that you can create prototype and test out the DynamoDB schema before ship to the actual AWS DynamoDB service in the cloud.

There're lots of benefits to doing that, for example once create a table in AWS DynamoDB service in the cloud you can't change the primary key, the partition, sort key, and local secondary index. Looks like it is what it is from the AWS at the moment I'm writing this blog, around 2020. It could change who knows.

Adding data to a DynamoDB table - node.js

After create a table to DynamoDB table, following example node.js code shows how to add random data to the this table.

Assume you create following code as, addData.js. run node addData.js from the command window. This code will generate 20 items to the table MyFakeFriend table. You could modify the max item from 20 to the number you want, for instance; adding ten of thousand data so you can do testing on the local environment before move to the AWS cloud.

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

function getAge() {
    return Math.floor(Math.random() * 120) + 1;
}

function addData() {
    AWS.config.update({
        region: "us-west-2",
        endpoint: "http://localhost:8000"
      });
      
    for (let index = 0; index < 20; index++) {
       
        var docClient = new AWS.DynamoDB.DocumentClient();
        var params = {
            TableName: 'MyFakeFriend',
            Item: {
                name: faker.name.findName(),
                age: getAge().toString(),
                phone: faker.phone.phoneNumber()
            }
        }
    
        docClient.put(params, function(err, data) {
            if (err) {
                console.error("Unable to add data", JSON.stringify(err, null, 2));
            } else {
                console.log("Able to add data", data);
            }
        })
    }
}
addData();

Test result by run scan the entire table

To test the result and make it simple, you can run the following command to scan the result from the table.

aws dynamodb scan --table-name MyFakeFriend --endpoint-url http://localhost:8000