SDK for JavaScript (v3) を使用した DynamoDB の例 - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

SDK for JavaScript (v3) を使用した DynamoDB の例

次のコード例は、DynamoDB で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、関連するシナリオやサービス間の例ではアクションのコンテキストが確認できます。

「シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

各例には、 へのリンクが含まれています。このリンクには GitHub、コンテキスト内でコードをセットアップして実行する方法の手順が記載されています。

開始方法

次のコード例は、DynamoDB の使用を開始する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import { ListTablesCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new ListTablesCommand({}); const response = await client.send(command); console.log(response.TableNames.join("\n")); return response; };
  • API の詳細については、「 API リファレンスListTables」の「」を参照してください。 AWS SDK for JavaScript

アクション

次のコード例では、DynamoDB テーブルを作成する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import { CreateTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new CreateTableCommand({ TableName: "EspressoDrinks", // For more information about data types, // see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes and // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors AttributeDefinitions: [ { AttributeName: "DrinkName", AttributeType: "S", }, ], KeySchema: [ { AttributeName: "DrinkName", KeyType: "HASH", }, ], ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, }); const response = await client.send(command); console.log(response); return response; };
SDK for JavaScript (v2)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { AttributeDefinitions: [ { AttributeName: "CUSTOMER_ID", AttributeType: "N", }, { AttributeName: "CUSTOMER_NAME", AttributeType: "S", }, ], KeySchema: [ { AttributeName: "CUSTOMER_ID", KeyType: "HASH", }, { AttributeName: "CUSTOMER_NAME", KeyType: "RANGE", }, ], ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, TableName: "CUSTOMER_LIST", StreamSpecification: { StreamEnabled: false, }, }; // Call DynamoDB to create the table ddb.createTable(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Table Created", data); } });

次のコード例では、DynamoDB テーブルを削除する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import { DeleteTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new DeleteTableCommand({ TableName: "DecafCoffees", }); const response = await client.send(command); console.log(response); return response; };
  • API の詳細については、「 API リファレンスDeleteTable」の「」を参照してください。 AWS SDK for JavaScript

SDK for JavaScript (v2)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { TableName: process.argv[2], }; // Call DynamoDB to delete the specified table ddb.deleteTable(params, function (err, data) { if (err && err.code === "ResourceNotFoundException") { console.log("Error: Table not found"); } else if (err && err.code === "ResourceInUseException") { console.log("Error: Table in use"); } else { console.log("Success", data); } });

次のコード例では、DynamoDB テーブルから項目を削除する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「」を参照してくださいDeleteCommand

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, DeleteCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new DeleteCommand({ TableName: "Sodas", Key: { Flavor: "Cola", }, }); const response = await docClient.send(command); console.log(response); return response; };
SDK for JavaScript (v2)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

テーブルから項目を削除します。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { TableName: "TABLE", Key: { KEY_NAME: { N: "VALUE" }, }, }; // Call DynamoDB to delete the item from the table ddb.deleteItem(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

DynamoDB ドキュメントクライアントを使用して、テーブルから項目を削除します。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { Key: { HASH_KEY: VALUE, }, TableName: "TABLE", }; docClient.delete(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

次のコード例は、DynamoDB 項目のバッチを取得する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「」を参照してくださいBatchGet

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { BatchGetCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new BatchGetCommand({ // Each key in this object is the name of a table. This example refers // to a Books table. RequestItems: { Books: { // Each entry in Keys is an object that specifies a primary key. Keys: [ { Title: "How to AWS", }, { Title: "DynamoDB for DBAs", }, ], // Only return the "Title" and "PageCount" attributes. ProjectionExpression: "Title, PageCount", }, }, }); const response = await docClient.send(command); console.log(response.Responses["Books"]); return response; };
SDK for JavaScript (v2)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { RequestItems: { TABLE_NAME: { Keys: [ { KEY_NAME: { N: "KEY_VALUE_1" } }, { KEY_NAME: { N: "KEY_VALUE_2" } }, { KEY_NAME: { N: "KEY_VALUE_3" } }, ], ProjectionExpression: "KEY_NAME, ATTRIBUTE", }, }, }; ddb.batchGetItem(params, function (err, data) { if (err) { console.log("Error", err); } else { data.Responses.TABLE_NAME.forEach(function (element, index, array) { console.log(element); }); } });

次のコード例では、DynamoDB テーブルから項目を取得する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「」を参照してくださいGetCommand

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, GetCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new GetCommand({ TableName: "AngryAnimals", Key: { CommonName: "Shoebill", }, }); const response = await docClient.send(command); console.log(response); return response; };
  • API の詳細については、「 API リファレンスGetItem」の「」を参照してください。 AWS SDK for JavaScript

SDK for JavaScript (v2)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

テーブルから項目を取得します。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { TableName: "TABLE", Key: { KEY_NAME: { N: "001" }, }, ProjectionExpression: "ATTRIBUTE_NAME", }; // Call DynamoDB to read the item from the table ddb.getItem(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Item); } });

DynamoDB ドキュメントクライアントを使用して、テーブルから項目を取得します。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { TableName: "EPISODES_TABLE", Key: { KEY_NAME: VALUE }, }; docClient.get(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Item); } });

次のコード例では、DynamoDB テーブルに関する情報を取得する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import { DescribeTableCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new DescribeTableCommand({ TableName: "Pastries", }); const response = await client.send(command); console.log(`TABLE NAME: ${response.Table.TableName}`); console.log(`TABLE ITEM COUNT: ${response.Table.ItemCount}`); return response; };
SDK for JavaScript (v2)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { TableName: process.argv[2], }; // Call DynamoDB to retrieve the selected table descriptions ddb.describeTable(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Table.KeySchema); } });

次のコード例では、DynamoDB テーブルを一覧表示する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import { ListTablesCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new ListTablesCommand({}); const response = await client.send(command); console.log(response); return response; };
SDK for JavaScript (v2)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); // Call DynamoDB to retrieve the list of tables ddb.listTables({ Limit: 10 }, function (err, data) { if (err) { console.log("Error", err.code); } else { console.log("Table names are ", data.TableNames); } });

次のコード例では、DynamoDB テーブルで項目を配置する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「」を参照してくださいPutCommand

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { PutCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new PutCommand({ TableName: "HappyAnimals", Item: { CommonName: "Shiba Inu", }, }); const response = await docClient.send(command); console.log(response); return response; };
  • API の詳細については、「 API リファレンスPutItem」の「」を参照してください。 AWS SDK for JavaScript

SDK for JavaScript (v2)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

テーブルに項目を配置します。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { TableName: "CUSTOMER_LIST", Item: { CUSTOMER_ID: { N: "001" }, CUSTOMER_NAME: { S: "Richard Roe" }, }, }; // Call DynamoDB to add the item to the table ddb.putItem(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

DynamoDB ドキュメントクライアントを使用して、テーブルに項目を配置します。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { TableName: "TABLE", Item: { HASHKEY: VALUE, ATTRIBUTE_1: "STRING_VALUE", ATTRIBUTE_2: VALUE_2, }, }; docClient.put(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

次のコード例では、DynamoDB テーブルに対してクエリを実行する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「」を参照してくださいQueryCommand

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { QueryCommand, DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new QueryCommand({ TableName: "CoffeeCrop", KeyConditionExpression: "OriginCountry = :originCountry AND RoastDate > :roastDate", ExpressionAttributeValues: { ":originCountry": "Ethiopia", ":roastDate": "2023-05-01", }, ConsistentRead: true, }); const response = await docClient.send(command); console.log(response); return response; };
SDK for JavaScript (v2)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB document client var docClient = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); var params = { ExpressionAttributeValues: { ":s": 2, ":e": 9, ":topic": "PHRASE", }, KeyConditionExpression: "Season = :s and Episode > :e", FilterExpression: "contains (Subtitle, :topic)", TableName: "EPISODES_TABLE", }; docClient.query(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.Items); } });

次のコードサンプルは、DynamoDB テーブルで PartiQL ステートメントを実行する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

PartiQL を使用して項目を作成します。

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { ExecuteStatementCommand, DynamoDBDocumentClient, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new ExecuteStatementCommand({ Statement: `INSERT INTO Flowers value {'Name':?}`, Parameters: ["Rose"], }); const response = await docClient.send(command); console.log(response); return response; };

PartiQL を使用して項目を取得します。

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { ExecuteStatementCommand, DynamoDBDocumentClient, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new ExecuteStatementCommand({ Statement: "SELECT * FROM CloudTypes WHERE IsStorm=?", Parameters: [false], ConsistentRead: true, }); const response = await docClient.send(command); console.log(response); return response; };

PartiQL を使用して項目を更新します。

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { ExecuteStatementCommand, DynamoDBDocumentClient, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new ExecuteStatementCommand({ Statement: "UPDATE EyeColors SET IsRecessive=? where Color=?", Parameters: [true, "blue"], }); const response = await docClient.send(command); console.log(response); return response; };

PartiQL を使用して項目を削除します。

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { ExecuteStatementCommand, DynamoDBDocumentClient, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new ExecuteStatementCommand({ Statement: "DELETE FROM PaintColors where Name=?", Parameters: ["Purple"], }); const response = await docClient.send(command); console.log(response); return response; };
  • API の詳細については、「 API リファレンスExecuteStatement」の「」を参照してください。 AWS SDK for JavaScript

次のコードサンプルは、DynamoDB テーブルで PartiQL ステートメントのバッチを実行する方法を示しています。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

PartiQL を使用して項目のバッチを作成します。

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, BatchExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const breakfastFoods = ["Eggs", "Bacon", "Sausage"]; const command = new BatchExecuteStatementCommand({ Statements: breakfastFoods.map((food) => ({ Statement: `INSERT INTO BreakfastFoods value {'Name':?}`, Parameters: [food], })), }); const response = await docClient.send(command); console.log(response); return response; };

PartiQL を使用して項目のバッチを取得します。

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, BatchExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new BatchExecuteStatementCommand({ Statements: [ { Statement: "SELECT * FROM PepperMeasurements WHERE Unit=?", Parameters: ["Teaspoons"], ConsistentRead: true, }, { Statement: "SELECT * FROM PepperMeasurements WHERE Unit=?", Parameters: ["Grams"], ConsistentRead: true, }, ], }); const response = await docClient.send(command); console.log(response); return response; };

PartiQL を使用して項目のバッチを更新します。

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, BatchExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const eggUpdates = [ ["duck", "fried"], ["chicken", "omelette"], ]; const command = new BatchExecuteStatementCommand({ Statements: eggUpdates.map((change) => ({ Statement: "UPDATE Eggs SET Style=? where Variety=?", Parameters: [change[1], change[0]], })), }); const response = await docClient.send(command); console.log(response); return response; };

PartiQL を使用して項目のバッチを削除します。

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, BatchExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new BatchExecuteStatementCommand({ Statements: [ { Statement: "DELETE FROM Flavors where Name=?", Parameters: ["Grape"], }, { Statement: "DELETE FROM Flavors where Name=?", Parameters: ["Strawberry"], }, ], }); const response = await docClient.send(command); console.log(response); return response; };
  • API の詳細については、「 API リファレンスBatchExecuteStatement」の「」を参照してください。 AWS SDK for JavaScript

次のコード例では、DynamoDB テーブルをスキャンする方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「」を参照してくださいScanCommand

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, ScanCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new ScanCommand({ ProjectionExpression: "#Name, Color, AvgLifeSpan", ExpressionAttributeNames: { "#Name": "Name" }, TableName: "Birds", }); const response = await docClient.send(command); for (const bird of response.Items) { console.log(`${bird.Name} - (${bird.Color}, ${bird.AvgLifeSpan})`); } return response; };
  • API の詳細については、「AWS SDK for JavaScript API リファレンス」の「Scan」を参照してください。

SDK for JavaScript (v2)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

// Load the AWS SDK for Node.js. var AWS = require("aws-sdk"); // Set the AWS Region. AWS.config.update({ region: "REGION" }); // Create DynamoDB service object. var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); const params = { // Specify which items in the results are returned. FilterExpression: "Subtitle = :topic AND Season = :s AND Episode = :e", // Define the expression attribute value, which are substitutes for the values you want to compare. ExpressionAttributeValues: { ":topic": { S: "SubTitle2" }, ":s": { N: 1 }, ":e": { N: 2 }, }, // Set the projection expression, which are the attributes that you want. ProjectionExpression: "Season, Episode, Title, Subtitle", TableName: "EPISODES_TABLE", }; ddb.scan(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); data.Items.forEach(function (element, index, array) { console.log( "printing", element.Title.S + " (" + element.Subtitle.S + ")" ); }); } });

次のコード例では、DynamoDB テーブルで項目を更新する方法を示します。

SDK for JavaScript (v3)
注記

には他にもがあります GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「」を参照してくださいUpdateCommand

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, UpdateCommand } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const command = new UpdateCommand({ TableName: "Dogs", Key: { Breed: "Labrador", }, UpdateExpression: "set Color = :color", ExpressionAttributeValues: { ":color": "black", }, ReturnValues: "ALL_NEW", }); const response = await docClient.send(command); console.log(response); return response; };
  • API の詳細については、「 API リファレンスUpdateItem」の「」を参照してください。 AWS SDK for JavaScript

次のコード例では、DynamoDB 項目のバッチを書き込む方法を示します。

SDK for JavaScript (v3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

この例では、ドキュメントクライアントを使用して DynamoDB での項目の操作を簡略化しています。API の詳細については、「」を参照してくださいBatchWrite

import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { BatchWriteCommand, DynamoDBDocumentClient, } from "@aws-sdk/lib-dynamodb"; import { readFileSync } from "fs"; // These modules are local to our GitHub repository. We recommend cloning // the project from GitHub if you want to run this example. // For more information, see https://github.com/awsdocs/aws-doc-sdk-examples. import { dirnameFromMetaUrl } from "@aws-sdk-examples/libs/utils/util-fs.js"; import { chunkArray } from "@aws-sdk-examples/libs/utils/util-array.js"; const dirname = dirnameFromMetaUrl(import.meta.url); const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); export const main = async () => { const file = readFileSync( `${dirname}../../../../../resources/sample_files/movies.json`, ); const movies = JSON.parse(file.toString()); // chunkArray is a local convenience function. It takes an array and returns // a generator function. The generator function yields every N items. const movieChunks = chunkArray(movies, 25); // For every chunk of 25 movies, make one BatchWrite request. for (const chunk of movieChunks) { const putRequests = chunk.map((movie) => ({ PutRequest: { Item: movie, }, })); const command = new BatchWriteCommand({ RequestItems: { // An existing table is required. A composite key of 'title' and 'year' is recommended // to account for duplicate titles. ["BatchWriteMoviesTable"]: putRequests, }, }); await docClient.send(command); } };
  • API の詳細については、「 API リファレンスBatchWriteItem」の「」を参照してください。 AWS SDK for JavaScript

SDK for JavaScript (v2)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create DynamoDB service object var ddb = new AWS.DynamoDB({ apiVersion: "2012-08-10" }); var params = { RequestItems: { TABLE_NAME: [ { PutRequest: { Item: { KEY: { N: "KEY_VALUE" }, ATTRIBUTE_1: { S: "ATTRIBUTE_1_VALUE" }, ATTRIBUTE_2: { N: "ATTRIBUTE_2_VALUE" }, }, }, }, { PutRequest: { Item: { KEY: { N: "KEY_VALUE" }, ATTRIBUTE_1: { S: "ATTRIBUTE_1_VALUE" }, ATTRIBUTE_2: { N: "ATTRIBUTE_2_VALUE" }, }, }, }, ], }, }; ddb.batchWriteItem(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });

シナリオ

次のコードサンプルは、以下の操作方法を示しています。

  • 映画データを保持できるテーブルを作成する。

  • テーブルに 1 つの映画を入れ、取得して更新する。

  • サンプル JSON ファイルから映画データをテーブルに書き込む。

  • 特定の年にリリースされた映画を照会する。

  • 何年もの間にリリースされた映画をスキャンする。

  • テーブルからムービーを削除し、テーブルを削除します。

SDK for JavaScript (v3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import { readFileSync } from "fs"; import { BillingMode, CreateTableCommand, DeleteTableCommand, DynamoDBClient, waitUntilTableExists, } from "@aws-sdk/client-dynamodb"; /** * This module is a convenience library. It abstracts Amazon DynamoDB's data type * descriptors (such as S, N, B, and BOOL) by marshalling JavaScript objects into * AttributeValue shapes. */ import { BatchWriteCommand, DeleteCommand, DynamoDBDocumentClient, GetCommand, PutCommand, UpdateCommand, paginateQuery, paginateScan, } from "@aws-sdk/lib-dynamodb"; // These modules are local to our GitHub repository. We recommend cloning // the project from GitHub if you want to run this example. // For more information, see https://github.com/awsdocs/aws-doc-sdk-examples. import { getUniqueName } from "@aws-sdk-examples/libs/utils/util-string.js"; import { dirnameFromMetaUrl } from "@aws-sdk-examples/libs/utils/util-fs.js"; import { chunkArray } from "@aws-sdk-examples/libs/utils/util-array.js"; const dirname = dirnameFromMetaUrl(import.meta.url); const tableName = getUniqueName("Movies"); const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); const log = (msg) => console.log(`[SCENARIO] ${msg}`); export const main = async () => { /** * Create a table. */ const createTableCommand = new CreateTableCommand({ TableName: tableName, // This example performs a large write to the database. // Set the billing mode to PAY_PER_REQUEST to // avoid throttling the large write. BillingMode: BillingMode.PAY_PER_REQUEST, // Define the attributes that are necessary for the key schema. AttributeDefinitions: [ { AttributeName: "year", // 'N' is a data type descriptor that represents a number type. // For a list of all data type descriptors, see the following link. // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors AttributeType: "N", }, { AttributeName: "title", AttributeType: "S" }, ], // The KeySchema defines the primary key. The primary key can be // a partition key, or a combination of a partition key and a sort key. // Key schema design is important. For more info, see // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html KeySchema: [ // The way your data is accessed determines how you structure your keys. // The movies table will be queried for movies by year. It makes sense // to make year our partition (HASH) key. { AttributeName: "year", KeyType: "HASH" }, { AttributeName: "title", KeyType: "RANGE" }, ], }); log("Creating a table."); const createTableResponse = await client.send(createTableCommand); log(`Table created: ${JSON.stringify(createTableResponse.TableDescription)}`); // This polls with DescribeTableCommand until the requested table is 'ACTIVE'. // You can't write to a table before it's active. log("Waiting for the table to be active."); await waitUntilTableExists({ client }, { TableName: tableName }); log("Table active."); /** * Add a movie to the table. */ log("Adding a single movie to the table."); // PutCommand is the first example usage of 'lib-dynamodb'. const putCommand = new PutCommand({ TableName: tableName, Item: { // In 'client-dynamodb', the AttributeValue would be required (`year: { N: 1981 }`) // 'lib-dynamodb' simplifies the usage ( `year: 1981` ) year: 1981, // The preceding KeySchema defines 'title' as our sort (RANGE) key, so 'title' // is required. title: "The Evil Dead", // Every other attribute is optional. info: { genres: ["Horror"], }, }, }); await docClient.send(putCommand); log("The movie was added."); /** * Get a movie from the table. */ log("Getting a single movie from the table."); const getCommand = new GetCommand({ TableName: tableName, // Requires the complete primary key. For the movies table, the primary key // is only the id (partition key). Key: { year: 1981, title: "The Evil Dead", }, // Set this to make sure that recent writes are reflected. // For more information, see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadConsistency.html. ConsistentRead: true, }); const getResponse = await docClient.send(getCommand); log(`Got the movie: ${JSON.stringify(getResponse.Item)}`); /** * Update a movie in the table. */ log("Updating a single movie in the table."); const updateCommand = new UpdateCommand({ TableName: tableName, Key: { year: 1981, title: "The Evil Dead" }, // This update expression appends "Comedy" to the list of genres. // For more information on update expressions, see // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html UpdateExpression: "set #i.#g = list_append(#i.#g, :vals)", ExpressionAttributeNames: { "#i": "info", "#g": "genres" }, ExpressionAttributeValues: { ":vals": ["Comedy"], }, ReturnValues: "ALL_NEW", }); const updateResponse = await docClient.send(updateCommand); log(`Movie updated: ${JSON.stringify(updateResponse.Attributes)}`); /** * Delete a movie from the table. */ log("Deleting a single movie from the table."); const deleteCommand = new DeleteCommand({ TableName: tableName, Key: { year: 1981, title: "The Evil Dead" }, }); await client.send(deleteCommand); log("Movie deleted."); /** * Upload a batch of movies. */ log("Adding movies from local JSON file."); const file = readFileSync( `${dirname}../../../../resources/sample_files/movies.json`, ); const movies = JSON.parse(file.toString()); // chunkArray is a local convenience function. It takes an array and returns // a generator function. The generator function yields every N items. const movieChunks = chunkArray(movies, 25); // For every chunk of 25 movies, make one BatchWrite request. for (const chunk of movieChunks) { const putRequests = chunk.map((movie) => ({ PutRequest: { Item: movie, }, })); const command = new BatchWriteCommand({ RequestItems: { [tableName]: putRequests, }, }); await docClient.send(command); } log("Movies added."); /** * Query for movies by year. */ log("Querying for all movies from 1981."); const paginatedQuery = paginateQuery( { client: docClient }, { TableName: tableName, //For more information about query expressions, see // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.html#Query.KeyConditionExpressions KeyConditionExpression: "#y = :y", // 'year' is a reserved word in DynamoDB. Indicate that it's an attribute // name by using an expression attribute name. ExpressionAttributeNames: { "#y": "year" }, ExpressionAttributeValues: { ":y": 1981 }, ConsistentRead: true, }, ); /** * @type { Record<string, any>[] }; */ const movies1981 = []; for await (const page of paginatedQuery) { movies1981.push(...page.Items); } log(`Movies: ${movies1981.map((m) => m.title).join(", ")}`); /** * Scan the table for movies between 1980 and 1990. */ log(`Scan for movies released between 1980 and 1990`); // A 'Scan' operation always reads every item in the table. If your design requires // the use of 'Scan', consider indexing your table or changing your design. // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-query-scan.html const paginatedScan = paginateScan( { client: docClient }, { TableName: tableName, // Scan uses a filter expression instead of a key condition expression. Scan will // read the entire table and then apply the filter. FilterExpression: "#y between :y1 and :y2", ExpressionAttributeNames: { "#y": "year" }, ExpressionAttributeValues: { ":y1": 1980, ":y2": 1990 }, ConsistentRead: true, }, ); /** * @type { Record<string, any>[] }; */ const movies1980to1990 = []; for await (const page of paginatedScan) { movies1980to1990.push(...page.Items); } log( `Movies: ${movies1980to1990 .map((m) => `${m.title} (${m.year})`) .join(", ")}`, ); /** * Delete the table. */ const deleteTableCommand = new DeleteTableCommand({ TableName: tableName }); log(`Deleting table ${tableName}.`); await client.send(deleteTableCommand); log("Table deleted."); };

次のコードサンプルは、以下の操作方法を示しています。

  • 複数の SELECT ステートメントを実行して、項目のバッチを取得する。

  • 複数の INSERT ステートメントを実行して、項目のバッチを追加する。

  • 複数の UPDATE ステートメントを実行して、項目のバッチを更新する。

  • 複数の DELETE ステートメントを実行して、項目のバッチを削除する。

SDK for JavaScript (v3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

PartiQL ステートメントのバッチを実行します。

import { BillingMode, CreateTableCommand, DeleteTableCommand, DynamoDBClient, waitUntilTableExists, } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, BatchExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); const log = (msg) => console.log(`[SCENARIO] ${msg}`); const tableName = "Cities"; export const main = async () => { /** * Create a table. */ log("Creating a table."); const createTableCommand = new CreateTableCommand({ TableName: tableName, // This example performs a large write to the database. // Set the billing mode to PAY_PER_REQUEST to // avoid throttling the large write. BillingMode: BillingMode.PAY_PER_REQUEST, // Define the attributes that are necessary for the key schema. AttributeDefinitions: [ { AttributeName: "name", // 'S' is a data type descriptor that represents a number type. // For a list of all data type descriptors, see the following link. // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors AttributeType: "S", }, ], // The KeySchema defines the primary key. The primary key can be // a partition key, or a combination of a partition key and a sort key. // Key schema design is important. For more info, see // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html KeySchema: [{ AttributeName: "name", KeyType: "HASH" }], }); await client.send(createTableCommand); log(`Table created: ${tableName}.`); /** * Wait until the table is active. */ // This polls with DescribeTableCommand until the requested table is 'ACTIVE'. // You can't write to a table before it's active. log("Waiting for the table to be active."); await waitUntilTableExists({ client }, { TableName: tableName }); log("Table active."); /** * Insert items. */ log("Inserting cities into the table."); const addItemsStatementCommand = new BatchExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.insert.html Statements: [ { Statement: `INSERT INTO ${tableName} value {'name':?, 'population':?}`, Parameters: ["Alachua", 10712], }, { Statement: `INSERT INTO ${tableName} value {'name':?, 'population':?}`, Parameters: ["High Springs", 6415], }, ], }); await docClient.send(addItemsStatementCommand); log(`Cities inserted.`); /** * Select items. */ log("Selecting cities from the table."); const selectItemsStatementCommand = new BatchExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.select.html Statements: [ { Statement: `SELECT * FROM ${tableName} WHERE name=?`, Parameters: ["Alachua"], }, { Statement: `SELECT * FROM ${tableName} WHERE name=?`, Parameters: ["High Springs"], }, ], }); const selectItemResponse = await docClient.send(selectItemsStatementCommand); log( `Got cities: ${selectItemResponse.Responses.map( (r) => `${r.Item.name} (${r.Item.population})`, ).join(", ")}`, ); /** * Update items. */ log("Modifying the populations."); const updateItemStatementCommand = new BatchExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.update.html Statements: [ { Statement: `UPDATE ${tableName} SET population=? WHERE name=?`, Parameters: [10, "Alachua"], }, { Statement: `UPDATE ${tableName} SET population=? WHERE name=?`, Parameters: [5, "High Springs"], }, ], }); await docClient.send(updateItemStatementCommand); log(`Updated cities.`); /** * Delete the items. */ log("Deleting the cities."); const deleteItemStatementCommand = new BatchExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.delete.html Statements: [ { Statement: `DELETE FROM ${tableName} WHERE name=?`, Parameters: ["Alachua"], }, { Statement: `DELETE FROM ${tableName} WHERE name=?`, Parameters: ["High Springs"], }, ], }); await docClient.send(deleteItemStatementCommand); log("Cities deleted."); /** * Delete the table. */ log("Deleting the table."); const deleteTableCommand = new DeleteTableCommand({ TableName: tableName }); await client.send(deleteTableCommand); log("Table deleted."); };
  • API の詳細については、「 API リファレンスBatchExecuteStatement」の「」を参照してください。 AWS SDK for JavaScript

次のコードサンプルは、以下の操作方法を示しています。

  • SELECT ステートメントを実行して項目を取得する。

  • INSERT 文を実行して項目を追加する。

  • UPDATE ステートメントを使用して項目を更新する。

  • DELETE ステートメントを実行して項目を削除する。

SDK for JavaScript (v3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

単一の PartiQL ステートメントを実行します。

import { BillingMode, CreateTableCommand, DeleteTableCommand, DynamoDBClient, waitUntilTableExists, } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient, ExecuteStatementCommand, } from "@aws-sdk/lib-dynamodb"; const client = new DynamoDBClient({}); const docClient = DynamoDBDocumentClient.from(client); const log = (msg) => console.log(`[SCENARIO] ${msg}`); const tableName = "SingleOriginCoffees"; export const main = async () => { /** * Create a table. */ log("Creating a table."); const createTableCommand = new CreateTableCommand({ TableName: tableName, // This example performs a large write to the database. // Set the billing mode to PAY_PER_REQUEST to // avoid throttling the large write. BillingMode: BillingMode.PAY_PER_REQUEST, // Define the attributes that are necessary for the key schema. AttributeDefinitions: [ { AttributeName: "varietal", // 'S' is a data type descriptor that represents a number type. // For a list of all data type descriptors, see the following link. // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.LowLevelAPI.html#Programming.LowLevelAPI.DataTypeDescriptors AttributeType: "S", }, ], // The KeySchema defines the primary key. The primary key can be // a partition key, or a combination of a partition key and a sort key. // Key schema design is important. For more info, see // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/best-practices.html KeySchema: [{ AttributeName: "varietal", KeyType: "HASH" }], }); await client.send(createTableCommand); log(`Table created: ${tableName}.`); /** * Wait until the table is active. */ // This polls with DescribeTableCommand until the requested table is 'ACTIVE'. // You can't write to a table before it's active. log("Waiting for the table to be active."); await waitUntilTableExists({ client }, { TableName: tableName }); log("Table active."); /** * Insert an item. */ log("Inserting a coffee into the table."); const addItemStatementCommand = new ExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.insert.html Statement: `INSERT INTO ${tableName} value {'varietal':?, 'profile':?}`, Parameters: ["arabica", ["chocolate", "floral"]], }); await client.send(addItemStatementCommand); log(`Coffee inserted.`); /** * Select an item. */ log("Selecting the coffee from the table."); const selectItemStatementCommand = new ExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.select.html Statement: `SELECT * FROM ${tableName} WHERE varietal=?`, Parameters: ["arabica"], }); const selectItemResponse = await docClient.send(selectItemStatementCommand); log(`Got coffee: ${JSON.stringify(selectItemResponse.Items[0])}`); /** * Update the item. */ log("Add a flavor profile to the coffee."); const updateItemStatementCommand = new ExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.update.html Statement: `UPDATE ${tableName} SET profile=list_append(profile, ?) WHERE varietal=?`, Parameters: [["fruity"], "arabica"], }); await client.send(updateItemStatementCommand); log(`Updated coffee`); /** * Delete the item. */ log("Deleting the coffee."); const deleteItemStatementCommand = new ExecuteStatementCommand({ // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ql-reference.delete.html Statement: `DELETE FROM ${tableName} WHERE varietal=?`, Parameters: ["arabica"], }); await docClient.send(deleteItemStatementCommand); log("Coffee deleted."); /** * Delete the table. */ log("Deleting the table."); const deleteTableCommand = new DeleteTableCommand({ TableName: tableName }); await client.send(deleteTableCommand); log("Table deleted."); };
  • API の詳細については、「 API リファレンスExecuteStatement」の「」を参照してください。 AWS SDK for JavaScript