Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8837

Node.jsからDynamoDBのテーブルの作成・削除と行追加・読み取り

$
0
0

表題の通りNode.jsからDynamoDBのテーブルの作成・削除と行追加・読み取りをメモします。
動作確認した後Qiita掲載用に少々手を入れているのでもしかしたら動かないかもしれません。

テーブルの作成

プライマリキーに「accessKey」を指定する場合

constAWS=require("aws-sdk");AWS.config.update({region:"ap-northeast-1"});// DynamoDB Local使うならendpointの指定が必要constdynamo_opt={apiVersion:'2012-08-10',endpoint:`http://localhost:8000`};constdynamodb=newAWS.DynamoDB(dynamo_opt);constdynamoCreateParams={TableName:"テーブル名",KeySchema:[{AttributeName:"accessKey",KeyType:"HASH"},],AttributeDefinitions:[{AttributeName:"accessKey",AttributeType:"S"}],ProvisionedThroughput:{ReadCapacityUnits:10,WriteCapacityUnits:10}};dynamodb.createTable(dynamoCreateParams,function(err,data){if(err){console.error("Unable to create table. Error JSON:",JSON.stringify(err));}else{console.log("Created table. Table description JSON:",JSON.stringify(data));}});

参考: テーブルの作成 - Amazon DynamoDB

行追加

プライマリキーのaccessKeyに加えuserIdも含めた行を3行追加する。

costtableName="テーブル名";vardynamoDataParams=[{TableName:tableName,Item:{"accessKey":"hoge","userId":1}},{TableName:tableName,Item:{"accessKey":"hage","userId":2}},{TableName:tableName,Item:{"accessKey":"fuga","userId":3}}];varddbClient=newAWS.DynamoDB.DocumentClient(dynamo_opt)varpromises=[];for(leti=0;i<dynamoDataParams.length;i++){(function(i){promises.push(ddbClient.put(dynamoDataParams[i]).promise());})(i);}Promise.all(promises).then(function(){console.log('done');})

行の読み取り

constdynamo_opt={apiVersion:'2012-08-10',endpoint:`http://localhost:8000`};constdynamo_params={TableName:"テーブル名",KeyConditionExpression:"accessKey = :a",ExpressionAttributeValues:{":a":"検索文字列"}};constddb=newAWS.DynamoDB.DocumentClient(dynamo_opt);ddb.query(dynamo_params,function(err,data){if(err){console.error('Unable to query:'+JSON.stringify(err));}else{console.log(JSON.stringify(data));}});

テーブルの削除

constAWS=require("aws-sdk");AWS.config.update({region:"ap-northeast-1"});// DynamoDB Local使うならendpointの指定が必要constdynamo_opt={apiVersion:'2012-08-10',endpoint:`http://localhost:8000`};constdynamodb=newAWS.DynamoDB(dynamo_opt);dynamodb.deleteTable({TableName:tableName},function(err,data){if(err){console.log("Unable to Delete table. Error JSON:",JSON.stringify(err));}else{console.log("Created table. Table description JSON:",JSON.stringify(data));}});

参考: テーブルの削除 - Amazon DynamoDB


Viewing all articles
Browse latest Browse all 8837

Trending Articles