DynamoDB에서 배치로 항목 읽기 및 쓰기 - AWS SDK for JavaScript

AWS SDK for JavaScript V3 API 참조 안내서는 AWS SDK for JavaScript 버전 3(V3)의 모든 API 작업을 자세히 설명합니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

DynamoDB에서 배치로 항목 읽기 및 쓰기

JavaScript code example that applies to Node.js execution

이 Node.js 코드 예제는 다음을 보여 줍니다.

  • DynamoDB 테이블에서 항목의 배치를 읽고 쓰는 방법

시나리오

이 예에서는 일련의 Node.js 모듈을 사용하여 항목의 배치를 DynamoDB 테이블에 넣고 항목의 배치를 읽습니다. 이 코드는 SDK for JavaScript에서 DynamoDB 클라이언트 클래스의 다음 메서드를 사용하여 배치 읽기 및 쓰기 작업을 수행합니다.

사전 필수 작업

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.

  • 이러한 노드 TypeScript 예를 실행하도록 프로젝트 환경을 설정하고 필수 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. GitHub의 지침을 따릅니다.

  • 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 보안 인증 파일 제공에 관한 자세한 내용은 AWS SDK 및 도구 참조 가이드Shared config and credentials files 단원을 참조하세요.

  • 액세스할 수 있는 항목이 포함된 DynamoDB 테이블을 생성합니다. DynamoDB 테이블 생성에 관한 자세한 내용은 DynamoDB에서 테이블 생성 및 사용 단원을 참조하세요.

중요

이 예에서는 ECMAScript6(ES6)를 사용합니다. 따라서 Node.js 버전 13.x 이상이 필요합니다. 최신 버전의 Node.js를 다운로드하여 설치하려면 Node.js downloads를 참조하세요.

그러나 CommonJS 구문을 사용하려는 경우 JavaScript ES6/CommonJS 구문 단원을 참조하세요.

참고

이 예에 사용된 데이터 형식에 관한 자세한 내용은 Amazon DynamoDB에서 지원되는 데이터 형식 및 명명 규칙을 참조하세요.

배치로 항목 읽기

파일 이름이 batch-get-item.js인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 다운로드를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 DynamoDB 클라이언트 서비스 객체를 생성합니다. 항목의 배치를 가져오는 데 필요한 파라미터를 포함하는 JSON 객체를 생성합니다. 이 예제에서는 읽을 하나 이상 테이블의 이름, 각 테이블에서 읽을 키의 값, 반환할 속성을 지정하는 프로젝션 표현식이 포함됩니다. DynamoDB 서비스 객체의 BatchGetItemCommand 메서드를 직접적으로 호출합니다.

import { BatchGetItemCommand, DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new BatchGetItemCommand({ RequestItems: { // Each key in this object is the name of a table. This example refers // to a PageAnalytics table. PageAnalytics: { // Each entry in Keys is an object that specifies a primary key. Keys: [ { // "PageName" is the partition key (simple primary key). // "S" specifies a string as the data type for the value "Home". // 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 PageName: { S: "Home" }, }, { PageName: { S: "About" }, }, ], // Only return the "PageName" and "PageViews" attributes. ProjectionExpression: "PageName, PageViews", }, }, }); const response = await client.send(command); console.log(response.Responses["PageAnalytics"]); return response; };

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다.

node batch-get-item.js

이 코드 예는 여기 GitHub에서 찾을 수 있습니다.

배치로 항목 쓰기

파일 이름이 batch-write-item.js인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 다운로드를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. DynamoDB에 액세스하려면 DynamoDB 클라이언트 서비스 객체를 생성합니다. 항목의 배치를 가져오는 데 필요한 파라미터가 포함된 JSON 객체를 생성합니다. 이 예에서는 객체에 항목을 쓰려는 테이블, 각 항목에 대해 쓰려는 키, 속성 및 해당 값이 포함됩니다. DynamoDB 서비스 객체의 BatchWriteItemCommand 메서드를 직접적으로 호출합니다.

import { BatchWriteItemCommand, DynamoDBClient, } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({}); export const main = async () => { const command = new BatchWriteItemCommand({ RequestItems: { // Each key in this object is the name of a table. This example refers // to a Coffees table. Coffees: [ // Each entry in Coffees is an object that defines either a PutRequest or DeleteRequest. { // Each PutRequest object defines one item to be inserted into the table. PutRequest: { // The keys of Item are attribute names. Each attribute value is an object with a data type and value. // For more information about data types, // see https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes Item: { Name: { S: "Donkey Kick" }, Process: { S: "Wet-Hulled" }, Flavors: { SS: ["Earth", "Syrup", "Spice"] }, }, }, }, { PutRequest: { Item: { Name: { S: "Flora Ethiopia" }, Process: { S: "Washed" }, Flavors: { SS: ["Stone Fruit", "Toasted Almond", "Delicate"] }, }, }, }, ], }, }); const response = await client.send(command); console.log(response); return response; };

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다.

node batch-write-item.js

이 코드 예는 여기 GitHub에서 찾을 수 있습니다.