使用 SDK 的 DynamoDB 示例 JavaScript V3 - AWS SDK for JavaScript

帮助我们改进AWS SDK for JavaScript版本 3 (V3) 文档,方法是使用反馈链接,或者在上创建议题或拉取请求GitHub.

这些区域有:AWS SDK for JavaScriptV3 API 参考指南详细描述了所有的 API 操作AWS SDK for JavaScript版本 3 (V3)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 SDK 的 DynamoDB 示例 JavaScript V3

以下代码示例显示如何使用AWS SDK for JavaScript使用 DynamoDB 的 V3。

操作展示如何调用具体的 DynamoDB 函数的代码节选。

方案展示如何通过调用多个 DynamoDB 函数来完成特定任务的代码示例。

每个示例都包含一个指向以下内容的链接 GitHub其中包含了有关如何在上下文中设置和运行代码的说明。

操作

以下代码示例显示如何创建 DynamoDB 表。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon DynamoDB service client object. const ddbClient = new DynamoDBClient({ region: REGION }); export { ddbClient };

创建 表。

// Import required AWS SDK clients and commands for Node.js import { CreateTableCommand } from "@aws-sdk/client-dynamodb"; import { ddbClient } from "./libs/ddbClient.js"; // Set the parameters export const params = { AttributeDefinitions: [ { AttributeName: "Season", //ATTRIBUTE_NAME_1 AttributeType: "N", //ATTRIBUTE_TYPE }, { AttributeName: "Episode", //ATTRIBUTE_NAME_2 AttributeType: "N", //ATTRIBUTE_TYPE }, ], KeySchema: [ { AttributeName: "Season", //ATTRIBUTE_NAME_1 KeyType: "HASH", }, { AttributeName: "Episode", //ATTRIBUTE_NAME_2 KeyType: "RANGE", }, ], ProvisionedThroughput: { ReadCapacityUnits: 1, WriteCapacityUnits: 1, }, TableName: "TEST_TABLE", //TABLE_NAME StreamSpecification: { StreamEnabled: false, }, }; export const run = async () => { try { const data = await ddbClient.send(new CreateTableCommand(params)); console.log("Table Created", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

// 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 表。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "REGION"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

删除 表。

// Import required AWS SDK clients and commands for Node.js import { DeleteTableCommand } from "@aws-sdk/client-dynamodb"; import { ddbClient } from "./libs/ddbClient.js"; // Set the parameters export const params = { TableName: "CUSTOMER_LIST_NEW", }; export const run = async () => { try { const data = await ddbClient.send(new DeleteTableCommand(params)); console.log("Success, table deleted", data); return data; } catch (err) { console.log("Error", err); } }; run();
  • 有关详细信息,请参阅。DeleteTableAWS SDK for JavaScriptAPI 参考.

适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

// 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 表中删除项目。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "REGION"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

使用 DynamoDB 文档客户端从表中删除项目。

import { DeleteCommand } from "@aws-sdk/lib-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; // Set the parameters. export const params = { TableName: "TABLE_NAME", Key: { primaryKey: "VALUE_1", sortKey: "VALUE_2", }, }; export const deleteItem = async () => { try { const data = await ddbDocClient.send(new DeleteCommand(params)); console.log("Success - item deleted"); } catch (err) { console.log("Error", err); } }; deleteItem();

使用 PartiQL 从表中删除项目。

// Import required AWS SDK clients and commands for Node.js. import { ExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; export const run = async (tableName, movieYear1, movieTitle1) => { const params = { Statement: "DELETE FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }; try { const data = await ddbDocClient.send(new ExecuteStatementCommand(params)); console.log("Success. Item deleted."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1);

使用 PartiQL 批量删除表中的项目。

// Import required AWS SDK clients and commands for Node.js. import { BatchExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const movieYear2 = process.argv[5]; const movieTitle2 = process.argv[6]; export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2 ) => { try { const params = { Statements: [ { Statement: "DELETE FROM " + tableName + " where year=? and title=?", Parameters: [{ N: movieYear1 }, { S: movieTitle1 }], }, { Statement: "DELETE FROM " + tableName + " where year=? and title=?", Parameters: [{ N: movieYear2 }, { S: movieTitle2 }], }, ], }; const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. Items deleted.", data); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1, movieYear2, movieTitle2);
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

从表中删除项目。

// 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 项目。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon DynamoDB service client object. const ddbClient = new DynamoDBClient({ region: REGION }); export { ddbClient };

获取项目。

// Import required AWS SDK clients and commands for Node.js import { BatchGetItemCommand } from "@aws-sdk/client-dynamodb"; import { ddbClient } from "./libs/ddbClient.js"; // Set the parameters export const params = { RequestItems: { TABLE_NAME: { Keys: [ { KEY_NAME_1: { N: "KEY_VALUE" }, KEY_NAME_2: { N: "KEY_VALUE" }, KEY_NAME_3: { N: "KEY_VALUE" }, }, ], ProjectionExpression: "ATTRIBUTE_NAME", }, }, }; export const run = async () => { try { const data = await ddbClient.send(new BatchGetItemCommand(params)); console.log("Success, items retrieved", data); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

// 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 表中获取项目。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "REGION"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建 DynamoDB 文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

从表中获取项目。

import { GetCommand } from "@aws-sdk/lib-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; // Set the parameters. export const params = { TableName: "TABLE_NAME", Key: { primaryKey: "VALUE_1", sortKey: "VALUE_2", }, }; export const getItem = async () => { try { const data = await ddbDocClient.send(new GetCommand(params)); console.log("Success :", data.Item); } catch (err) { console.log("Error", err); } }; getItem();

使用 PartiQL 从表中获取项目。

// Import required AWS SDK clients and commands for Node.js. import { ExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient"; const tableName = process.argv[2]; const movieTitle1 = process.argv[3]; export const run = async (tableName, movieTitle1) => { const params = { Statement: "SELECT * FROM " + tableName + " where title=?", Parameters: [{ S: movieTitle1 }], }; try { const data = await ddbDocClient.send(new ExecuteStatementCommand(params)); for (let i = 0; i < data.Items.length; i++) { console.log( "Success. The query return the following data. Item " + i, data.Items[i].year, data.Items[i].title, data.Items[i].info ); } return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieTitle1);

使用 PartiQL 从表中批量获取项目。

// Import required AWS SDK clients and commands for Node.js. import { BatchExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const movieYear2 = process.argv[5]; const movieTitle2 = process.argv[6]; export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2 ) => { const params = { Statements: [ { Statement: "SELECT * FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }, { Statement: "SELECT * FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle2 }, { N: movieYear2 }], }, ], }; try { const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); for (let i = 0; i < data.Responses.length; i++) { console.log(data.Responses[i].Item.year); console.log(data.Responses[i].Item.title); } return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1, movieYear2, movieTitle2);
  • 有关详细信息,请参阅。GetItemAWS SDK for JavaScriptAPI 参考.

适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

从表中获取项目。

// 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 表的信息。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon DynamoDB service client object. const ddbClient = new DynamoDBClient({ region: REGION }); export { ddbClient };

描述表。

// Import required AWS SDK clients and commands for Node.js import { DescribeTableCommand } from "@aws-sdk/client-dynamodb"; import { ddbClient } from "./libs/ddbClient.js"; // Set the parameters export const params = { TableName: "TABLE_NAME" }; //TABLE_NAME export const run = async () => { try { const data = await ddbClient.send(new DescribeTableCommand(params)); console.log("Success", data); // console.log("Success", data.Table.KeySchema); return data; } catch (err) { console.log("Error", err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

// 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 表。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon DynamoDB service client object. const ddbClient = new DynamoDBClient({ region: REGION }); export { ddbClient };

列出表。

// Import required AWS SDK clients and commands for Node.js import { ListTablesCommand } from "@aws-sdk/client-dynamodb"; import { ddbClient } from "./libs/ddbClient.js"; export const run = async () => { try { const data = await ddbClient.send(new ListTablesCommand({})); console.log(data); // console.log(data.TableNames.join("\n")); return data; } catch (err) { console.error(err); } }; run();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

// 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 表中。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "REGION"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建 DynamoDB 文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

使用 DynamoDB 文档客户端将项目放入表中。

import { PutCommand } from "@aws-sdk/lib-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; export const putItem = async () => { // Set the parameters. export const params = { TableName: "TABLE_NAME", Item: { primaryKey: "VALUE_1", sortKey: "VALUE_2", }, }; try { const data = await ddbDocClient.send(new PutCommand(params)); console.log("Success - item added or updated", data); } catch (err) { console.log("Error", err.stack); } }; putItem();

使用 PartiQL 将项目放入表中。

// Import required AWS SDK clients and commands for Node.js. import { ExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; export const run = async (tableName, movieTitle1, movieYear1) => { const params = { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }; try { const data = await ddbDocClient.send(new ExecuteStatementCommand(params)); console.log("Success. Item added."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieTitle1, movieYear1);

使用 PartiQL 批量将项目放入表中。

// Import required AWS SDK clients and commands for Node.js. import { BatchExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const movieYear2 = process.argv[5]; const movieTitle2 = process.argv[6]; export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2 ) => { const params = { Statements: [ { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }, { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle2 }, { N: movieYear2 }], }, ], }; try { const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. Items added."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1, movieYear2, movieTitle2);
  • 有关详细信息,请参阅。PutItemAWS SDK for JavaScriptAPI 参考.

适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

将项目放入表中。

// 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 表。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon DynamoDB service client object. const ddbClient = new DynamoDBClient({ region: REGION }); export { ddbClient };

查询表。

// Import required AWS SDK clients and commands for Node.js import { QueryCommand } from "@aws-sdk/client-dynamodb"; import { ddbClient } from "./libs/ddbClient.js"; // Set the parameters export const params = { KeyConditionExpression: "Season = :s and Episode > :e", FilterExpression: "contains (Subtitle, :topic)", ExpressionAttributeValues: { ":s": { N: "1" }, ":e": { N: "2" }, ":topic": { S: "SubTitle" }, }, ProjectionExpression: "Episode, Title, Subtitle", TableName: "EPISODES_TABLE", }; export const run = async () => { try { const data = await ddbClient.send(new QueryCommand(params)); return data; data.Items.forEach(function (element, index, array) { console.log(element.Title.S + " (" + element.Subtitle.S + ")"); }); } catch (err) { console.error(err); } }; run();

为 DynamoDB 文档客户端创建客户端。

// Create service client module using ES6 syntax. import { DynamoDBDocumentClient} from "@aws-sdk/lib-dynamodb"; import {ddbClient} from "./ddbClient"; const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB Document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

使用 DynamoDB 文档客户端查询表。

import { QueryCommand } from "@aws-sdk/lib-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; // Set the parameters. export const params = { ExpressionAttributeNames: { "#r": "rank", "#y": "year" }, ProjectionExpression: "#r, #y, title", TableName: "TABLE_NAME", ExpressionAttributeValues: { ":t": "MOVIE_NAME", ":y": "MOVIE_YEAR", ":r": "MOVIE_RANK", }, KeyConditionExpression: "title = :t and #y = :y", FilterExpression: "info.#r = :r", }; export const queryTable = async () => { try { const data = await ddbDocClient.send(new QueryCommand(params)); for (let i = 0; i < data.Items.length; i++) { console.log( "Success. Items with rank of " + "MOVIE_RANK" + " include\n" + "Year = " + data.Items[i].year + " Title = " + data.Items[i].title ); } } catch (err) { console.log("Error", err); } }; queryTable();
适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

// 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 语句。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "eu-west-1"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建 DynamoDB 文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "eu-west-1"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

使用 PartiQL 创建项目。

// Import required AWS SDK clients and commands for Node.js. import { ExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; export const run = async (tableName, movieTitle1, movieYear1) => { const params = { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }; try { const data = await ddbDocClient.send(new ExecuteStatementCommand(params)); console.log("Success. Item added."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieTitle1, movieYear1);

使用 PartiQL 获取项目。

// Import required AWS SDK clients and commands for Node.js. import { ExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient"; const tableName = process.argv[2]; const movieTitle1 = process.argv[3]; export const run = async (tableName, movieTitle1) => { const params = { Statement: "SELECT * FROM " + tableName + " where title=?", Parameters: [{ S: movieTitle1 }], }; try { const data = await ddbDocClient.send(new ExecuteStatementCommand(params)); for (let i = 0; i < data.Items.length; i++) { console.log( "Success. The query return the following data. Item " + i, data.Items[i].year, data.Items[i].title, data.Items[i].info ); } return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieTitle1);

使用 PartiQL 更新项目。

// Import required AWS SDK clients and commands for Node.js. import { ExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const producer1 = process.argv[5]; export const run = async (tableName, movieYear1, movieTitle1, producer1) => { const params = { Statement: "UPDATE " + tableName + " SET Producer=? where title=? and year=?", Parameters: [{ S: producer1 }, { S: movieTitle1 }, { N: movieYear1 }], }; try { const data = await ddbDocClient.send(new ExecuteStatementCommand(params)); console.log("Success. Item updated."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1, producer1);

使用 PartiQL 删除项目。

// Import required AWS SDK clients and commands for Node.js. import { ExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; export const run = async (tableName, movieYear1, movieTitle1) => { const params = { Statement: "DELETE FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }; try { const data = await ddbDocClient.send(new ExecuteStatementCommand(params)); console.log("Success. Item deleted."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1);
  • 有关详细信息,请参阅。ExecuteStatementAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何对 DynamoDB 表运行批量 PartiQL 语句。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "eu-west-1"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建 DynamoDB 文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "eu-west-1"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

使用 PartiQL 创建一批项目。

// Import required AWS SDK clients and commands for Node.js. import { BatchExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const movieYear2 = process.argv[5]; const movieTitle2 = process.argv[6]; export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2 ) => { const params = { Statements: [ { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }, { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle2 }, { N: movieYear2 }], }, ], }; try { const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. Items added."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1, movieYear2, movieTitle2);

使用 PartiQL 获取一批项目。

// Import required AWS SDK clients and commands for Node.js. import { BatchExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const movieYear2 = process.argv[5]; const movieTitle2 = process.argv[6]; export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2 ) => { const params = { Statements: [ { Statement: "SELECT * FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }, { Statement: "SELECT * FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle2 }, { N: movieYear2 }], }, ], }; try { const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); for (let i = 0; i < data.Responses.length; i++) { console.log(data.Responses[i].Item.year); console.log(data.Responses[i].Item.title); } return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1, movieYear2, movieTitle2);

使用 PartiQL 更新一批项目。

// Import required AWS SDK clients and commands for Node.js. import { BatchExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const movieYear2 = process.argv[6]; const movieTitle2 = process.argv[7]; const producer1 = process.argv[5]; const producer2 = process.argv[8]; export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2, producer1, producer2 ) => { const params = { Statements: [ { Statement: "UPDATE " + tableName + " SET producer=? where title=? and year=?", Parameters: [{ S: producer1 }, { S: movieTitle1 }, { N: movieYear1 }], }, { Statement: "UPDATE " + tableName + " SET producer=? where title=? and year=?", Parameters: [{ S: producer2 }, { S: movieTitle2 }, { N: movieYear2 }], }, ], }; try { const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. Items updated."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2, producer1, producer2 );

使用 PartiQL 删除一批项目。

// Import required AWS SDK clients and commands for Node.js. import { BatchExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const movieYear2 = process.argv[5]; const movieTitle2 = process.argv[6]; export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2 ) => { try { const params = { Statements: [ { Statement: "DELETE FROM " + tableName + " where year=? and title=?", Parameters: [{ N: movieYear1 }, { S: movieTitle1 }], }, { Statement: "DELETE FROM " + tableName + " where year=? and title=?", Parameters: [{ N: movieYear2 }, { S: movieTitle2 }], }, ], }; const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. Items deleted.", data); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1, movieYear2, movieTitle2);

以下代码示例显示如何扫描 DynamoDB 表。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "REGION"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建 DynamoDB 文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

使用 DynamoDB 文档客户端扫描表。

// Import required AWS SDK clients and commands for Node.js. import { ddbDocClient } from "../libs/ddbDocClient.js"; import { ScanCommand } from "@aws-sdk/lib-dynamodb"; // Set the parameters. export const params = { TableName: "TABLE_NAME", ProjectionExpression: "#r, #y, title", ExpressionAttributeNames: { "#r": "rank", "#y": "year" }, FilterExpression: "title = :t and #y = :y and info.#r = :r", ExpressionAttributeValues: { ":r": "MOVIE_RANK", ":y": "MOVIE_YEAR", ":t": "MOVIE_NAME", }, }; export const scanTable = async () => { try { const data = await ddbDocClient.send(new ScanCommand(params)); console.log("success", data.Items); } catch (err) { console.log("Error", err); } }; scanTable();
  • 有关 API 详细信息,请参阅《AWS SDK for JavaScript API 参考》中的 Scan

适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

// 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 表中的项目。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "REGION"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建 DynamoDB 文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

使用 DynamoDB 文档客户端更新表中的项目。

import { UpdateCommand } from "@aws-sdk/lib-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; export const updateItem = async () => { // Set the parameters. const params = { TableName: "TABLE_NAME", Key: { title: "MOVIE_NAME", year: "MOVIE_YEAR", }, ProjectionExpression: "#r", ExpressionAttributeNames: { "#r": "rank" }, UpdateExpression: "set info.plot = :p, info.#r = :r", ExpressionAttributeValues: { ":p": "MOVIE_PLOT", ":r": "MOVIE_RANK", }, }; try { const data = await ddbDocClient.send(new UpdateCommand(params)); console.log("Success - item added or updated", data); return data; } catch (err) { console.log("Error", err); } }; updateItem();

使用 PartiQL 更新表中的项目。

// Import required AWS SDK clients and commands for Node.js. import { ExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const producer1 = process.argv[5]; export const run = async (tableName, movieYear1, movieTitle1, producer1) => { const params = { Statement: "UPDATE " + tableName + " SET Producer=? where title=? and year=?", Parameters: [{ S: producer1 }, { S: movieTitle1 }, { N: movieYear1 }], }; try { const data = await ddbDocClient.send(new ExecuteStatementCommand(params)); console.log("Success. Item updated."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run(tableName, movieYear1, movieTitle1, producer1);

使用 PartiQL 在表中批量更新项目。

// Import required AWS SDK clients and commands for Node.js. import { BatchExecuteStatementCommand } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; const tableName = process.argv[2]; const movieYear1 = process.argv[3]; const movieTitle1 = process.argv[4]; const movieYear2 = process.argv[6]; const movieTitle2 = process.argv[7]; const producer1 = process.argv[5]; const producer2 = process.argv[8]; export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2, producer1, producer2 ) => { const params = { Statements: [ { Statement: "UPDATE " + tableName + " SET producer=? where title=? and year=?", Parameters: [{ S: producer1 }, { S: movieTitle1 }, { N: movieYear1 }], }, { Statement: "UPDATE " + tableName + " SET producer=? where title=? and year=?", Parameters: [{ S: producer2 }, { S: movieTitle2 }, { N: movieYear2 }], }, ], }; try { const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. Items updated."); return "Run successfully"; // For unit tests. } catch (err) { console.error(err); } }; run( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2, producer1, producer2 );
  • 有关详细信息,请参阅。UpdateItemAWS SDK for JavaScriptAPI 参考.

以下代码示例显示如何写入一批 DynamoDB 项目。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "REGION"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

将项目添加到表中。

import fs from "fs"; import * as R from "ramda"; import { ddbDocClient } from "../libs/ddbDocClient.js"; import { BatchWriteCommand } from "@aws-sdk/lib-dynamodb"; export const writeData = async () => { // Before you run this example, download 'movies.json' from https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Js.02.html, // and put it in the same folder as the example. // Get the movie data parse to convert into a JSON object. const allMovies = JSON.parse(fs.readFileSync("moviedata.json", "utf8")); // Split the table into segments of 25. const dataSegments = R.splitEvery(25, allMovies); const TABLE_NAME = "TABLE_NAME" try { // Loop batch write operation 10 times to upload 250 items. for (let i = 0; i < 10; i++) { const segment = dataSegments[i]; for (let j = 0; j < 25; j++) { const params = { RequestItems: { [TABLE_NAME]: [ { // Destination Amazon DynamoDB table name. PutRequest: { Item: { year: segment[j].year, title: segment[j].title, info: segment[j].info, }, }, }, ], }, }; const data = ddbDocClient.send(new BatchWriteCommand(params)); } console.log("Success, table updated."); } } catch (error) { console.log("Error", error); } }; writeData();
  • 有关详细信息,请参阅。BatchWriteItemAWS SDK for JavaScriptAPI 参考.

适用于的开发工具包 JavaScript V2
提示

要了解如何设置和运行此示例,请参阅GitHub.

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

场景

以下代码示例显示了如何:

  • 创建一个可以保存电影数据的表。

  • 放置、获取和更新表中的单部电影。

  • 从示例 JSON 文件将电影数据写入表中。

  • 查询在给定年份发行的电影。

  • 扫描几年内发行的电影。

  • 从表中删除电影。

  • 删除 表。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建 DynamoDB 客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "REGION"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建 DynamoDB 文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

运行场景。

*/ import fs from "fs"; // A practical functional library used to split the data into segments. import * as R from "ramda"; import { ddbClient } from "../libs/ddbClient.js"; import { CreateTableCommand, DeleteTableCommand, } from "@aws-sdk/client-dynamodb"; import { ddbDocClient } from "../libs/ddbDocClient.js"; import { PutCommand, GetCommand, UpdateCommand, BatchWriteCommand, DeleteCommand, ScanCommand, QueryCommand, } from "@aws-sdk/lib-dynamodb"; if (process.argv.length < 6) { console.log( "Usage: node dynamodb_basics.js <tableNaame> <newMovieName> <newMovieYear> <existingMovieName> <existingMovieYear> <newMovieRank> <newMoviePlot>\n" + "Example: node dynamodb_basics.js newmoviesbrmur newmoviename 2025 200 'MOVIE PLOT DETAILS'" ); } // Helper function to delay running the code while the AWS service calls wait for responses. function wait(ms) { var start = Date.now(); var end = start; while (end < start + ms) { end = Date.now(); } } // Set the parameters. const tableName = process.argv[2]; const newMovieName = process.argv[3]; const newMovieYear = parseInt(process.argv[4]); // parseInt() converts the string into a number. const existingMovieName = process.argv[5]; const existingMovieYear = parseInt(process.argv[6]); const newMovieRank = parseInt(process.argv[7]); const newMoviePlot = process.argv[8]; export const run = async ( tableName, newMovieName, newMovieYear, existingMovieName, existingMovieYear, newMovieRank, newMoviePlot ) => { try { console.log("Creating table ..."); // Set the parameters. const params = { AttributeDefinitions: [ { AttributeName: "title", AttributeType: "S", }, { AttributeName: "year", AttributeType: "N", }, ], KeySchema: [ { AttributeName: "title", KeyType: "HASH", }, { AttributeName: "year", KeyType: "RANGE", }, ], ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5, }, TableName: tableName, }; const data = await ddbClient.send(new CreateTableCommand(params)); console.log("Waiting for table to be created..."); wait(10000); console.log( "Table created. Table name is ", data.TableDescription.TableName ); try { const params = { TableName: tableName, Item: { title: newMovieName, year: newMovieYear, }, }; console.log("Adding movie..."); const data = await ddbDocClient.send(new PutCommand(params)); console.log("Success - single movie added."); try { // Before you run this example, download 'movies.json' from https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Js.02.html, // and put it in the same folder as the example. // Get the movie data parse to convert into a JSON object. const allMovies = JSON.parse(fs.readFileSync("moviedata.json", "utf8")); // Split the table into segments of 25. const dataSegments = R.splitEvery(25, allMovies); // Loop batch write operation 10 times to upload 250 items. console.log("Writing movies in batch to table..."); for (let i = 0; i < 10; i++) { const segment = dataSegments[i]; for (let j = 0; j < 25; j++) { const params = { RequestItems: { [tableName]: [ { // Destination Amazon DynamoDB table name. PutRequest: { Item: { year: segment[j].year, title: segment[j].title, info: segment[j].info, }, }, }, ], }, }; const data = ddbDocClient.send(new BatchWriteCommand(params)); } } wait(20000); console.log("Success, movies written to table."); try { const params = { TableName: tableName, Key: { title: existingMovieName, year: existingMovieYear, }, // Define expressions for the new or updated attributes. ProjectionExpression: "#r", ExpressionAttributeNames: { "#r": "rank" }, UpdateExpression: "set info.plot = :p, info.#r = :r", ExpressionAttributeValues: { ":p": newMoviePlot, ":r": newMovieRank, }, ReturnValues: "ALL_NEW", }; console.log("Updating a single movie..."); const data = await ddbClient.send(new UpdateCommand(params)); console.log("Success - movie updated."); try { console.log("Getting movie...."); const params = { TableName: tableName, Key: { title: existingMovieName, year: existingMovieYear, }, }; const data = await ddbDocClient.send(new GetCommand(params)); console.log("Success getting item. Item details :", data.Item); try { const params = { TableName: tableName, Key: { title: newMovieName, year: newMovieYear, }, }; const data = await ddbDocClient.send(new DeleteCommand(params)); console.log("Success - movie deleted."); try { console.log("Scanning table...."); const params = { TableName: tableName, ProjectionExpression: "#r, #y, title", ExpressionAttributeNames: { "#r": "rank", "#y": "year" }, FilterExpression: "title = :t and #y = :y and info.#r = :r", ExpressionAttributeValues: { ":r": newMovieRank, ":y": existingMovieYear, ":t": existingMovieName, }, }; const data = await ddbClient.send(new ScanCommand(params)); // Loop through and parse the response. for (let i = 0; i < data.Items.length; i++) { console.log( "Scan successful. Items with rank of " + newMovieRank + " include\n" + "Year = " + data.Items[i].year + " Title = " + data.Items[i].title ); } try { const params = { ExpressionAttributeNames: { "#r": "rank", "#y": "year" }, ProjectionExpression: "#r, #y, title", TableName: tableName, UpdateExpression: "set #r = :r, title = :t, #y = :y", ExpressionAttributeValues: { ":t": existingMovieName, ":y": existingMovieYear, ":r": newMovieRank, }, KeyConditionExpression: "title = :t and #y = :y", FilterExpression: "info.#r = :r", }; console.log("Querying table..."); const data = await ddbDocClient.send( new QueryCommand(params) ); // Loop through and parse the response. for (let i = 0; i < data.Items.length; i++) { console.log( "Query successful. Items with rank of " + newMovieRank + " include\n" + "Year = " + data.Items[i].year + " Title = " + data.Items[i].title ); } try { console.log("Deleting a movie..."); const params = { TableName: tableName, Key: { title: existingMovieName, year: existingMovieYear, }, }; const data = await ddbDocClient.send( new DeleteCommand(params) ); console.log("Success - item deleted"); try { console.log("Deleting the table..."); const params = { TableName: tableName, }; const data = await ddbDocClient.send( new DeleteTableCommand(params) ); console.log("Success, table deleted."); return "Run successfully"; // For unit tests. } catch (err) { console.log("Error deleting table. ", err); } } catch (err) { console.log("Error deleting movie. ", err); } } catch (err) { console.log("Error querying table. ", err); } } catch (err) { console.log("Error scanning table. ", err); } } catch (err) { console.log("Error deleting movie. ", err); } } catch (err) { console.log("Error getting item. ", err); } } catch (err) { console.log("Error adding movies by batch. ", err); } } catch (err) { console.log("Error updating item. ", err); } } catch (err) { console.log("Error adding a single item. ", err); } } catch (err) { console.log("Error creating table. ", err); } }; run( tableName, newMovieName, newMovieYear, existingMovieName, existingMovieYear, newMovieRank, newMoviePlot );

以下代码示例显示了如何:

  • 通过运行多个 SELECT 语句获取一批项目。

  • 通过运行多个 INSERT 语句添加一批项目。

  • 通过运行多个 UPDATE 语句更新一批项目。

  • 通过运行多个 DELETE 语句删除一批项目。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "eu-west-1"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "eu-west-1"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

批量查询项目。

*/ import fs from "fs"; // A practical functional library used to split the data into segments. import * as R from "ramda"; import { ddbClient } from "../libs/ddbClient.js"; import { ddbDocClient } from "../libs/ddbDocClient.js"; import { BatchWriteCommand } from "@aws-sdk/lib-dynamodb"; import { CreateTableCommand, BatchExecuteStatementCommand, } from "@aws-sdk/client-dynamodb"; if (process.argv.length < 6) { console.log( "Usage: node partiQL_basics.js <tableName> <movieTitle1> <movieYear1> <movieTitle1> <movieYear1> <producer1> <producer2> \n" + "Example: node partiQL_basics.js Movies_batch 2006 'The Departed' 2013 '2 Guns' 'New View Films' 'Old Thyme Films'" ); } const tableName = process.argv[2]; const movieYear1 = parseInt(process.argv[3]); const movieTitle1 = process.argv[4]; const movieYear2 = parseInt(process.argv[5]); const movieTitle2 = process.argv[6]; const producer1 = process.argv[7]; const producer2 = process.argv[8]; // Helper function to delay running the code while the AWS service calls wait for responses. function wait(ms) { var start = Date.now(); var end = start; while (end < start + ms) { end = Date.now(); } } // Set the parameters. export const run = async ( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2, producer1, producer2 ) => { try { console.log("Creating table ..."); // Set the parameters. const params = { AttributeDefinitions: [ { AttributeName: "title", AttributeType: "S", }, { AttributeName: "year", AttributeType: "N", }, ], KeySchema: [ { AttributeName: "title", KeyType: "HASH", }, { AttributeName: "year", KeyType: "RANGE", }, ], ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5, }, TableName: tableName, }; const data = await ddbClient.send(new CreateTableCommand(params)); console.log("Waiting for table to be created..."); wait(10000); console.log( "Table created. Table name is ", data.TableDescription.TableName ); try { // Before you run this example, download 'movies.json' from https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Js.02.html, // and put it in the same folder as the example. // Get the movie data parse to convert into a JSON object. const allMovies = JSON.parse(fs.readFileSync("moviedata.json", "utf8")); // Split the table into segments of 25. const dataSegments = R.splitEvery(25, allMovies); // Loop batch write operation 10 times to upload 250 items. console.log("Writing movies in batch to table..."); for (let i = 0; i < 10; i++) { const segment = dataSegments[i]; for (let j = 0; j < 25; j++) { const params = { RequestItems: { [tableName]: [ { // Destination Amazon DynamoDB table name. PutRequest: { Item: { year: segment[j].year, title: segment[j].title, info: segment[j].info, }, }, }, ], }, }; const data = ddbDocClient.send(new BatchWriteCommand(params)); } } wait(10000); console.log("Success, movies written to table."); try { console.log("Getting movie...."); const params = { Statements: [ { Statement: "SELECT * FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }, { Statement: "SELECT * FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle2 }, { N: movieYear2 }], }, ], }; const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. The query return the following data.", data); for (let i = 0; i < data.Responses.length; i++) { console.log(data.Responses[i].Item.year); console.log(data.Responses[i].Item.title); } try { const params = { Statements: [ { Statement: "DELETE FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }, { Statement: "DELETE FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle2 }, { N: movieYear2 }], }, ], }; const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. Items deleted by batch."); try { const params = { Statements: [ { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }, { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle2 }, { N: movieYear2 }], }, ], }; const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. Items added by batch."); try { const params = { Statements: [ { Statement: "UPDATE " + tableName + " SET Producer=? where title=? and year=?", Parameters: [ { S: producer1 }, { S: movieTitle1 }, { N: movieYear1 }, ], }, { Statement: "UPDATE " + tableName + " SET Producer=? where title=? and year=?", Parameters: [ { S: producer2 }, { S: movieTitle2 }, { N: movieYear2 }, ], }, ], }; console.log("Updating movies..."); const data = await ddbDocClient.send( new BatchExecuteStatementCommand(params) ); console.log("Success. Items updated by batch."); return "Run successfully"; // For unit tests. } catch (err) { console.log("Error updating items by batch. ", err); } } catch (err) { console.log("Error adding items to table by batch. ", err); } } catch (err) { console.log("Error deleting movies by batch. ", err); } } catch (err) { console.log("Error getting movies by batch. ", err); } } catch (err) { console.log("Error adding movies by batch. ", err); } } catch (err) { console.log("Error creating table. ", err); } }; run( tableName, movieYear1, movieTitle1, movieYear2, movieTitle2, producer1, producer2 );

以下代码示例显示了如何:

  • 通过运行一个 SELECT 语句获取一个项目。

  • 通过运行一个 INSERT 语句添加一个项目。

  • 通过运行一个 UPDATE 语句更新一个项目。

  • 通过运行一个 DELETE 语句删除一个项目。

适用于的开发工具包 JavaScript V3
提示

要了解如何设置和运行此示例,请参阅GitHub.

创建客户端。

// Create the DynamoDB service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. export const REGION = "eu-west-1"; // For example, "us-east-1". // Create an Amazon DynamoDB service client object. export const ddbClient = new DynamoDBClient({ region: REGION });

创建文档客户端。

// Create a service client module using ES6 syntax. import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; import { ddbClient } from "./ddbClient.js"; // Set the AWS Region. const REGION = "eu-west-1"; // For example, "us-east-1". const marshallOptions = { // Whether to automatically convert empty strings, blobs, and sets to `null`. convertEmptyValues: false, // false, by default. // Whether to remove undefined values while marshalling. removeUndefinedValues: false, // false, by default. // Whether to convert typeof object to map attribute. convertClassInstanceToMap: false, // false, by default. }; const unmarshallOptions = { // Whether to return numbers as a string instead of converting them to native JavaScript numbers. wrapNumbers: false, // false, by default. }; const translateConfig = { marshallOptions, unmarshallOptions }; // Create the DynamoDB document client. const ddbDocClient = DynamoDBDocumentClient.from(ddbClient, translateConfig); export { ddbDocClient };

查询单个项目。

*/ import fs from "fs"; // A practical functional library used to split the data into segments. import * as R from "ramda"; import { ddbClient } from "../libs/ddbClient.js"; import { ddbDocClient } from "../libs/ddbDocClient.js"; import { BatchWriteCommand } from "@aws-sdk/lib-dynamodb"; import { CreateTableCommand, ExecuteStatementCommand, } from "@aws-sdk/client-dynamodb"; if (process.argv.length < 6) { console.log( "Usage: node partiQL_basics.js <tableName> <movieYear1> <movieTitle1> <producer1>\n" + "Example: node partiQL_basics.js Movies 2006 'The Departed' 'New View Films'" ); } // Helper function to delay running the code while the AWS service calls wait for responses. function wait(ms) { var start = Date.now(); var end = start; while (end < start + ms) { end = Date.now(); } } const tableName = process.argv[2]; const movieTitle1 = process.argv[3]; const movieYear1 = process.argv[4]; const producer1 = process.argv[5]; export const run = async (tableName, movieYear1, movieTitle1, producer1) => { try { console.log("Creating table ..."); // Set the parameters. const params = { AttributeDefinitions: [ { AttributeName: "title", AttributeType: "S", }, { AttributeName: "year", AttributeType: "N", }, ], KeySchema: [ { AttributeName: "title", KeyType: "HASH", }, { AttributeName: "year", KeyType: "RANGE", }, ], ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5, }, TableName: tableName, }; const data = await ddbClient.send(new CreateTableCommand(params)); console.log("Waiting for table to be created..."); wait(10000); console.log( "Table created. Table name is ", data.TableDescription.TableName ); try { // Before you run this example, download 'movies.json' from https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Js.02.html, // and put it in the same folder as the example. // Get the movie data parse to convert into a JSON object. const allMovies = JSON.parse(fs.readFileSync("moviedata.json", "utf8")); // Split the table into segments of 25. const dataSegments = R.splitEvery(25, allMovies); // Loop batch write operation 10 times to upload 250 items. console.log("Writing movies in batch to table..."); for (let i = 0; i < 10; i++) { const segment = dataSegments[i]; for (let j = 0; j < 25; j++) { const params = { RequestItems: { [tableName]: [ { // Destination Amazon DynamoDB table name. PutRequest: { Item: { year: segment[j].year, title: segment[j].title, info: segment[j].info, }, }, }, ], }, }; const data = ddbDocClient.send(new BatchWriteCommand(params)); } } wait(20000); console.log("Success, movies written to table."); try { const params = { Statement: "SELECT * FROM " + tableName + " where title=?", Parameters: [{ S: movieTitle1 }], }; console.log("Getting movie...."); console.log("Statement", params.Statement); const data = await ddbDocClient.send( new ExecuteStatementCommand(params) ); for (let i = 0; i < data.Items.length; i++) { console.log( "Success. The query return the following data. Item " + i, data.Items[i].year, data.Items[i].title, data.Items[i].info ); } try { const params = { Statement: "DELETE FROM " + tableName + " where title=? and year=?", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }; const data = await ddbDocClient.send( new ExecuteStatementCommand(params) ); console.log("Success. Item deleted."); try { const params = { Statement: "INSERT INTO " + tableName + " value {'title':?, 'year':?}", Parameters: [{ S: movieTitle1 }, { N: movieYear1 }], }; const data = await ddbDocClient.send( new ExecuteStatementCommand(params) ); console.log("Success. Item added."); try { const params = { Statement: "UPDATE " + tableName + " SET Producer=? where title=? and year=?", Parameters: [ { S: producer1 }, { S: movieTitle1 }, { N: movieYear1 }, ], }; console.log("Updating a single movie..."); const data = await ddbDocClient.send( new ExecuteStatementCommand(params) ); console.log("Success. Item updated."); return "Run successfully"; // For unit tests. } catch (err) { console.log("Error updating item. ", err); } } catch (err) { console.log("Error adding items to table. ", err); } } catch (err) { console.log("Error deleting movie. ", err); } } catch (err) { console.log("Error getting movie. ", err); } } catch (err) { console.log("Error adding movies by batch. ", err); } } catch (err) { console.log("Error creating table. ", err); } }; run(tableName, movieYear1, movieTitle1, producer1);