Node.js
DynamoDB

Node.js で DynamoDB を使う (テーブル Movies)

AWS のマニュアルのサンプルを私なりにアレンジしてみました。
AWS のマニュアルは、以下です。
 ステップ 1: テーブルを作成する
 ステップ 2: サンプルデータをロードする
 ステップ 3: 項目を作成、読み込み、更新、削除する

プログラムを動かすには、ローカルで DynamoDB が動いている必要があります。
テーブル名は、 Movies です。

リージョンを、 "ap-northeast-1" に、したのと、サンプルの moviedata.json を小さくしたのが主な変更です。

1) テーブルの作成

dynamo_create_table.js
#! /usr/bin/node

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

AWS.config.update({
  region: "ap-northeast-1",
  endpoint: "http://localhost:8000"
});

var dynamodb = new AWS.DynamoDB();

var params = {
    TableName : "Movies",
    KeySchema: [       
        { AttributeName: "year", KeyType: "HASH"},  //Partition key
        { AttributeName: "title", KeyType: "RANGE" }  //Sort key
    ],
    AttributeDefinitions: [       
        { AttributeName: "year", AttributeType: "N" },
        { AttributeName: "title", AttributeType: "S" }
    ],
    ProvisionedThroughput: {       
        ReadCapacityUnits: 5, 
        WriteCapacityUnits: 5
    }
};

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

2) テーブルの削除

dynamo_delete_table.js
#! /usr/bin/node

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

AWS.config.update({
  region: "ap-northeast-1",
  endpoint: "http://localhost:8000"
});

var dynamodb = new AWS.DynamoDB();

var params = {
    TableName : "Movies",
    KeySchema: [       
        { AttributeName: "year", KeyType: "HASH"},  //Partition key
        { AttributeName: "title", KeyType: "RANGE" }  //Sort key
    ],
    AttributeDefinitions: [       
        { AttributeName: "year", AttributeType: "N" },
        { AttributeName: "title", AttributeType: "S" }
    ],
    ProvisionedThroughput: {       
        ReadCapacityUnits: 5, 
        WriteCapacityUnits: 5
    }
};

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

3) データの挿入

dynamo_loaddata.js
#! /usr/bin/node

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

AWS.config.update({
    region: "ap-northeast-1",
    endpoint: "http://localhost:8000"
});

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

console.log("Importing movies into DynamoDB. Please wait.");

const file_json = 'moviedata.json'

var allMovies = JSON.parse(fs.readFileSync(file_json, 'utf8'));
allMovies.forEach(function(movie) {
    var params = {
        TableName: "Movies",
        Item: {
            "year":  movie.year,
            "title": movie.title,
            "info":  movie.info
        }
    };

    docClient.put(params, function(err, data) {
       if (err) {
           console.error("Unable to add movie", movie.title, ". Error JSON:", JSON.stringify(err, null, 2));
       } else {
           console.log("PutItem succeeded:", movie.title);
       }
    });
});

小さくした JSON ファイル

moviedata.json
[
    {
        "year": 2013,
        "title": "Rush",
        "info": {
            "directors": ["Ron Howard"],
            "release_date": "2013-09-02T00:00:00Z",
            "rating": 8.3,
            "genres": [
                "Action",
                "Biography",
                "Drama",
                "Sport"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTQyMDE0MTY0OV5BMl5BanBnXkFtZTcwMjI2OTI0OQ@@._V1_SX400_.jpg",
            "plot": "A re-creation of the merciless 1970s rivalry between Formula One rivals James Hunt and Niki Lauda.",
            "rank": 2,
            "running_time_secs": 7380,
            "actors": [
                "Daniel Bruhl",
                "Chris Hemsworth",
                "Olivia Wilde"
            ]
        }
    },
    {
        "year": 2013,
        "title": "Prisoners",
        "info": {
            "directors": ["Denis Villeneuve"],
            "release_date": "2013-08-30T00:00:00Z",
            "rating": 8.2,
            "genres": [
                "Crime",
                "Drama",
                "Thriller"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTg0NTIzMjQ1NV5BMl5BanBnXkFtZTcwNDc3MzM5OQ@@._V1_SX400_.jpg",
            "plot": "When Keller Dover's daughter and her friend go missing, he takes matters into his own hands as the police pursue multiple leads and the pressure mounts. But just how far will this desperate father go to protect his family?",
            "rank": 3,
            "running_time_secs": 9180,
            "actors": [
                "Hugh Jackman",
                "Jake Gyllenhaal",
                "Viola Davis"
            ]
        }
    },
    {
        "year": 2013,
        "title": "The Hunger Games: Catching Fire",
        "info": {
            "directors": ["Francis Lawrence"],
            "release_date": "2013-11-11T00:00:00Z",
            "genres": [
                "Action",
                "Adventure",
                "Sci-Fi",
                "Thriller"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTAyMjQ3OTAxMzNeQTJeQWpwZ15BbWU4MDU0NzA1MzAx._V1_SX400_.jpg",
            "plot": "Katniss Everdeen and Peeta Mellark become targets of the Capitol after their victory in the 74th Hunger Games sparks a rebellion in the Districts of Panem.",
            "rank": 4,
            "running_time_secs": 8760,
            "actors": [
                "Jennifer Lawrence",
                "Josh Hutcherson",
                "Liam Hemsworth"
            ]
        }
    },
    {
        "year": 2013,
        "title": "Thor: The Dark World",
        "info": {
            "directors": ["Alan Taylor"],
            "release_date": "2013-10-30T00:00:00Z",
            "genres": [
                "Action",
                "Adventure",
                "Fantasy"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTQyNzAwOTUxOF5BMl5BanBnXkFtZTcwMTE0OTc5OQ@@._V1_SX400_.jpg",
            "plot": "Faced with an enemy that even Odin and Asgard cannot withstand, Thor must embark on his most perilous and personal journey yet, one that will reunite him with Jane Foster and force him to sacrifice everything to save us all.",
            "rank": 5,
            "actors": [
                "Chris Hemsworth",
                "Natalie Portman",
                "Tom Hiddleston"
            ]
        }
    },
    {
        "year": 2013,
        "title": "This Is the End",
        "info": {
            "directors": [
                "Evan Goldberg",
                "Seth Rogen"
            ],
            "release_date": "2013-06-03T00:00:00Z",
            "rating": 7.2,
            "genres": [
                "Comedy",
                "Fantasy"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTQxODE3NjM1Ml5BMl5BanBnXkFtZTcwMzkzNjc4OA@@._V1_SX400_.jpg",
            "plot": "While attending a party at James Franco's house, Seth Rogen, Jay Baruchel and many other celebrities are faced with the apocalypse.",
            "rank": 6,
            "running_time_secs": 6420,
            "actors": [
                "James Franco",
                "Jonah Hill",
                "Seth Rogen"
            ]
        }
    },
    {
        "year": 2013,
        "title": "Insidious: Chapter 2",
        "info": {
            "directors": ["James Wan"],
            "release_date": "2013-09-13T00:00:00Z",
            "rating": 7.1,
            "genres": [
                "Horror",
                "Thriller"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTg0OTA5ODIxNF5BMl5BanBnXkFtZTcwNTUzNDg4OQ@@._V1_SX400_.jpg",
            "plot": "The haunted Lambert family seeks to uncover the mysterious childhood secret that has left them dangerously connected to the spirit world.",
            "rank": 7,
            "running_time_secs": 6360,
            "actors": [
                "Patrick Wilson",
                "Rose Byrne",
                "Barbara Hershey"
            ]
        }
    },
    {
        "year": 2013,
        "title": "World War Z",
        "info": {
            "directors": ["Marc Forster"],
            "release_date": "2013-06-02T00:00:00Z",
            "rating": 7.1,
            "genres": [
                "Action",
                "Adventure",
                "Horror",
                "Sci-Fi",
                "Thriller"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTg0NTgxMjIxOF5BMl5BanBnXkFtZTcwMDM0MDY1OQ@@._V1_SX400_.jpg",
            "plot": "United Nations employee Gerry Lane traverses the world in a race against time to stop the Zombie pandemic that is toppling armies and governments, and threatening to destroy humanity itself.",
            "rank": 8,
            "running_time_secs": 6960,
            "actors": [
                "Brad Pitt",
                "Mireille Enos",
                "Daniella Kertesz"
            ]
        }
    },
    {
        "year": 2014,
        "title": "X-Men: Days of Future Past",
        "info": {
            "directors": ["Bryan Singer"],
            "release_date": "2014-05-21T00:00:00Z",
            "genres": [
                "Action",
                "Adventure",
                "Fantasy",
                "Sci-Fi"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTQ0NzIwNTA1MV5BMl5BanBnXkFtZTgwNjY2OTcwMDE@._V1_SX400_.jpg",
            "plot": "The X-Men send Wolverine to the past to change a major historical event that could globally impact man and mutant kind.",
            "rank": 9,
            "actors": [
                "Jennifer Lawrence",
                "Hugh Jackman",
                "Michael Fassbender"
            ]
        }
    },
    {
        "year": 2014,
        "title": "Transformers: Age of Extinction",
        "info": {
            "directors": ["Michael Bay"],
            "release_date": "2014-06-25T00:00:00Z",
            "genres": [
                "Action",
                "Adventure",
                "Sci-Fi"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTQyMDA5Nzg0Nl5BMl5BanBnXkFtZTgwNzA4NDcxMDE@._V1_SX400_.jpg",
            "plot": "A mechanic and his daughter make a discovery that brings down Autobots and Decepticons - and a paranoid government official - on them.",
            "rank": 10,
            "actors": [
                "Mark Wahlberg",
                "Nicola Peltz",
                "Jack Reynor"
            ]
        }
    },
    {
        "year": 2013,
        "title": "Now You See Me",
        "info": {
            "directors": ["Louis Leterrier"],
            "release_date": "2013-05-21T00:00:00Z",
            "rating": 7.3,
            "genres": [
                "Crime",
                "Mystery",
                "Thriller"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTY0NDY3MDMxN15BMl5BanBnXkFtZTcwOTM5NzMzOQ@@._V1_SX400_.jpg",
            "plot": "An FBI agent and an Interpol detective track a team of illusionists who pull off bank heists during their performances and reward their audiences with the money.",
            "rank": 11,
            "running_time_secs": 6900,
            "actors": [
                "Jesse Eisenberg",
                "Common",
                "Mark Ruffalo"
            ]
        }
    },
    {
        "year": 2013,
        "title": "Gravity",
        "info": {
            "directors": ["Alfonso Cuaron"],
            "release_date": "2013-08-28T00:00:00Z",
            "rating": 8.2,
            "genres": [
                "Drama",
                "Sci-Fi",
                "Thriller"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BNjE5MzYwMzYxMF5BMl5BanBnXkFtZTcwOTk4MTk0OQ@@._V1_SX400_.jpg",
            "plot": "A medical engineer and an astronaut work together to survive after an accident leaves them adrift in space.",
            "rank": 12,
            "running_time_secs": 5400,
            "actors": [
                "Sandra Bullock",
                "George Clooney",
                "Ed Harris"
            ]
        }
    },
    {
        "year": 2013,
        "title": "We're the Millers",
        "info": {
            "directors": ["Rawson Marshall Thurber"],
            "release_date": "2013-08-03T00:00:00Z",
            "rating": 7.2,
            "genres": [
                "Comedy",
                "Crime"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMjA5Njc0NDUxNV5BMl5BanBnXkFtZTcwMjYzNzU1OQ@@._V1_SX400_.jpg",
            "plot": "A veteran pot dealer creates a fake family as part of his plan to move a huge shipment of weed into the U.S. from Mexico.",
            "rank": 13,
            "running_time_secs": 6600,
            "actors": [
                "Jason Sudeikis",
                "Jennifer Aniston",
                "Emma Roberts"
            ]
        }
    },
    {
        "year": 2013,
        "title": "Riddick",
        "info": {
            "directors": ["David Twohy"],
            "release_date": "2013-09-04T00:00:00Z",
            "rating": 6.8,
            "genres": [
                "Action",
                "Sci-Fi",
                "Thriller"
            ],
            "image_url": "http://ia.media-imdb.com/images/M/MV5BMTk5NzYwMzQ4MV5BMl5BanBnXkFtZTcwMjE5MTI1OQ@@._V1_SX400_.jpg",
            "plot": "Left for dead on a sun-scorched planet, Riddick finds himself up against an alien race of predators. Activating an emergency beacon alerts two ships: one carrying a new breed of mercenary, the other captained by a man from Riddick's past.",
            "rank": 14,
            "running_time_secs": 7140,
            "actors": [
                "Vin Diesel",
                "Karl Urban",
                "Katee Sackhoff"
            ]
        }
    }
]

4) データのスキャン

dynamo_read.js
#! /usr/bin/node
// ---------------------------------------------------------------
//  dynamo_read.js
//
//                  Dec/19/2017
//
// ---------------------------------------------------------------
function scan_proc (docClient)
{
    const tbl_name = "Movies"

    var params = {TableName: tbl_name}

    docClient.scan(params, function(err, data)
        {
        if (err) {
            console.error("Unable to get " + tbl_name,JSON.stringify(err, null, 2))

            }
         else {
            var str_out = ""
            data.Items.forEach(function(film) {
            const json_str = JSON.stringify(film)
            str_out += film.year + "\t"
                + film.info.rating + "\t"
                 + film.title + "\n"
                })

            console.log(str_out)
            }
        })
}

// ---------------------------------------------------------------
console.error ("*** 開始 ***")

var AWS = require("aws-sdk")

AWS.config.update({
    region: "ap-northeast-1",
    endpoint: 'http://localhost:8000'
})

var docClient = new AWS.DynamoDB.DocumentClient()

scan_proc (docClient)

console.error ("*** 終了 ***")

// ---------------------------------------------------------------

5) データの追加

dynamo_append.js
#! /usr/bin/node

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

AWS.config.update({
  region: "ap-northeast-1",
  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": "Nothing happens at all.",
            "rating": 1
        }
    }
};

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

6) データの削除

dynamo_delete.js
#! /usr/bin/node

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

AWS.config.update({
  region: "ap-northeast-1",
  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,
    Key:{
        "year":year,
        "title":title
    },
};

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

簡単なテーブルの例
https://qiita.com/ekzemplaro/items/3ceb1399b11329fe9111