27
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Lambda(js)とDynamoDBを連携する

Last updated at Posted at 2016-09-15

やりたいこと

LambdaでDynamoDBに書き込んだり読み込んだりしたいのです。

取得

方法

  1. DynamoDBでテーブルを作る
    2. テーブルの作成でテーブル名、プライマリキーを設定する
  2. DynamoDBの読み書きができるIAMロールを作る
    4. IAMロールでDynamoDBのフルアクセス権を付けたロールを作る
  3. Lambdaでコードを書く
var AWS = require('aws-sdk'),
    dynamo = new AWS.DynamoDB();

exports.scan = function( event, context ) {
  dynamo.scan( {
    "TableName": "TableName"
  }, function( err, data ) {
    console.log( JSON.stringify( data ) );
  } )
};

結果

"S"とか、"N"とかいらないから、オブジェクトでほしかった。。。

{
  "Items":
  [{
    "key1":{
      "S":"value1"
    },
    "key2":{
      "S":"value2"
    },
    "primaryKey":{
      "N":"0"
    }
  }],
  "Count":1,
  "ScannedCount":1
}

いい感じのオブジェクト形式で取得する方法(追記)

  • DynamoDBクライアントを変更します。
var AWS = require('aws-sdk'),
    documentClient = new AWS.DynamoDB.DocumentClient();

exports.scan = function( event, context ) {
  documentClient .scan( {
    "TableName": "TableName"
  }, function( err, data ) {
    console.log( JSON.stringify( data ) );
  } )
};

書き込み

方法

var AWS = require('aws-sdk'),
    documentClient = new AWS.DynamoDB.DocumentClient();

exports.scan = function( event, context ) {
  documentClient .put( {
    "TableName": "TableName",
    "Item": {
      "primaryKey": 0,
      "key1": "hello",
      "key2": "world!"
    }
  }, function( err, data ) {

  } )
};

結果

SnapCrab_NoName_2016-9-16_9-7-9_No-00.png

27
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?