예: AWS SDK for .NET 하위 수준 API를 사용하는 일괄 작업 - Amazon DynamoDB

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

예: AWS SDK for .NET 하위 수준 API를 사용하는 일괄 작업

이번 단원에서는 배치 쓰기, 배치 가져오기 같이 Amazon DynamoDB에서 지원되는 배치 작업의 예제를 제공합니다.

예: AWS SDK for .NET 하위 수준 API를 사용하는 일괄 쓰기 작업

다음 C# 코드는 BatchWriteItem 메서드를 사용해 업로드 및 삭제 작업을 실행하는 예제입니다.

  • 한 항목을 Forum 테이블에 업로드합니다.

  • 한 항목을 Thread 테이블에서 업로드하고 삭제합니다.

일괄 쓰기 요청을 생성할 때는 하나 이상의 테이블에 대해 업로드 및 삭제 요청을 얼마든지 지정할 수 있습니다. 하지만 DynamoDB BatchWriteItem은 단일 배치 쓰기 작업에서 배치 쓰기 요청의 크기와 업로드 및 삭제 작업의 수를 제한합니다. 자세한 내용은 을 참조하십시오 BatchWriteItem. 이러한 제한을 초과할 경우에는 요청이 거부됩니다. 이러한 요청을 처리하는 데 충분한 처리량이 테이블에 할당되어 있지 않은 경우에는 응답 시 처리되지 않은 요청 항목이 반환됩니다.

다음은 응답을 확인하여 처리되지 않은 요청 항목의 유무를 점검하는 예제입니다. 미처리 요청 항목이 있는 경우에는 루프백이 발생하여 미처리 항목이 있는 BatchWriteItem 요청을 다시 보냅니다. DynamoDB에서 테이블 생성 및 코드 예시에 대한 데이터 로드의 단계를 따랐다면 이미 ForumThread 테이블은 생성되어 있을 것입니다. 이러한 샘플 테이블은 프로그래밍 방식으로 생성하여 업로드할 수도 있습니다. 자세한 설명은 를 사용하여 예제 테이블 생성 및 데이터 업로드 AWS SDK for .NET 섹션을 참조하세요.

다음 샘플을 테스트하기 위한 step-by-step 지침은 을 참조하십시오.NET 코드 예시.

using System; using System.Collections.Generic; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; namespace com.amazonaws.codesamples { class LowLevelBatchWrite { private static string table1Name = "Forum"; private static string table2Name = "Thread"; private static AmazonDynamoDBClient client = new AmazonDynamoDBClient(); static void Main(string[] args) { try { TestBatchWrite(); } catch (AmazonServiceException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } Console.WriteLine("To continue, press Enter"); Console.ReadLine(); } private static void TestBatchWrite() { var request = new BatchWriteItemRequest { ReturnConsumedCapacity = "TOTAL", RequestItems = new Dictionary<string, List<WriteRequest>> { { table1Name, new List<WriteRequest> { new WriteRequest { PutRequest = new PutRequest { Item = new Dictionary<string, AttributeValue> { { "Name", new AttributeValue { S = "S3 forum" } }, { "Threads", new AttributeValue { N = "0" }} } } } } }, { table2Name, new List<WriteRequest> { new WriteRequest { PutRequest = new PutRequest { Item = new Dictionary<string, AttributeValue> { { "ForumName", new AttributeValue { S = "S3 forum" } }, { "Subject", new AttributeValue { S = "My sample question" } }, { "Message", new AttributeValue { S = "Message Text." } }, { "KeywordTags", new AttributeValue { SS = new List<string> { "S3", "Bucket" } } } } } }, new WriteRequest { // For the operation to delete an item, if you provide a primary key value // that does not exist in the table, there is no error, it is just a no-op. DeleteRequest = new DeleteRequest { Key = new Dictionary<string, AttributeValue>() { { "ForumName", new AttributeValue { S = "Some partition key value" } }, { "Subject", new AttributeValue { S = "Some sort key value" } } } } } } } } }; CallBatchWriteTillCompletion(request); } private static void CallBatchWriteTillCompletion(BatchWriteItemRequest request) { BatchWriteItemResponse response; int callCount = 0; do { Console.WriteLine("Making request"); response = client.BatchWriteItem(request); callCount++; // Check the response. var tableConsumedCapacities = response.ConsumedCapacity; var unprocessed = response.UnprocessedItems; Console.WriteLine("Per-table consumed capacity"); foreach (var tableConsumedCapacity in tableConsumedCapacities) { Console.WriteLine("{0} - {1}", tableConsumedCapacity.TableName, tableConsumedCapacity.CapacityUnits); } Console.WriteLine("Unprocessed"); foreach (var unp in unprocessed) { Console.WriteLine("{0} - {1}", unp.Key, unp.Value.Count); } Console.WriteLine(); // For the next iteration, the request will have unprocessed items. request.RequestItems = unprocessed; } while (response.UnprocessedItems.Count > 0); Console.WriteLine("Total # of batch write API calls made: {0}", callCount); } } }

예: AWS SDK for .NET 하위 수준 API를 사용하는 일괄 가져오기 작업

다음 C# 코드 예제에서는 BatchGetItem 메서드를 사용해 Amazon DynamoDB의 ForumThread 테이블에서 다수의 항목을 가져옵니다. BatchGetItemRequest는 테이블 이름을 비롯해 각 테이블의 기본 키 목록을 지정합니다. 이 예제는 가져온 항목을 출력하여 응답을 처리합니다.

DynamoDB에서 테이블 생성 및 코드 예시에 대한 데이터 로드의 단계를 따랐다면 이미 샘플 데이터와 함께 이 테이블들이 생성되어 있을 것입니다. 이러한 샘플 테이블은 프로그래밍 방식으로 생성하여 업로드할 수도 있습니다. 자세한 설명은 를 사용하여 예제 테이블 생성 및 데이터 업로드 AWS SDK for .NET 섹션을 참조하세요.

다음 샘플을 테스트하기 위한 step-by-step 지침은 을 참조하십시오.NET 코드 예시.

using System; using System.Collections.Generic; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; namespace com.amazonaws.codesamples { class LowLevelBatchGet { private static string table1Name = "Forum"; private static string table2Name = "Thread"; private static AmazonDynamoDBClient client = new AmazonDynamoDBClient(); static void Main(string[] args) { try { RetrieveMultipleItemsBatchGet(); Console.WriteLine("To continue, press Enter"); Console.ReadLine(); } catch (AmazonServiceException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } } private static void RetrieveMultipleItemsBatchGet() { var request = new BatchGetItemRequest { RequestItems = new Dictionary<string, KeysAndAttributes>() { { table1Name, new KeysAndAttributes { Keys = new List<Dictionary<string, AttributeValue> >() { new Dictionary<string, AttributeValue>() { { "Name", new AttributeValue { S = "Amazon DynamoDB" } } }, new Dictionary<string, AttributeValue>() { { "Name", new AttributeValue { S = "Amazon S3" } } } } }}, { table2Name, new KeysAndAttributes { Keys = new List<Dictionary<string, AttributeValue> >() { new Dictionary<string, AttributeValue>() { { "ForumName", new AttributeValue { S = "Amazon DynamoDB" } }, { "Subject", new AttributeValue { S = "DynamoDB Thread 1" } } }, new Dictionary<string, AttributeValue>() { { "ForumName", new AttributeValue { S = "Amazon DynamoDB" } }, { "Subject", new AttributeValue { S = "DynamoDB Thread 2" } } }, new Dictionary<string, AttributeValue>() { { "ForumName", new AttributeValue { S = "Amazon S3" } }, { "Subject", new AttributeValue { S = "S3 Thread 1" } } } } } } } }; BatchGetItemResponse response; do { Console.WriteLine("Making request"); response = client.BatchGetItem(request); // Check the response. var responses = response.Responses; // Attribute list in the response. foreach (var tableResponse in responses) { var tableResults = tableResponse.Value; Console.WriteLine("Items retrieved from table {0}", tableResponse.Key); foreach (var item1 in tableResults) { PrintItem(item1); } } // Any unprocessed keys? could happen if you exceed ProvisionedThroughput or some other error. Dictionary<string, KeysAndAttributes> unprocessedKeys = response.UnprocessedKeys; foreach (var unprocessedTableKeys in unprocessedKeys) { // Print table name. Console.WriteLine(unprocessedTableKeys.Key); // Print unprocessed primary keys. foreach (var key in unprocessedTableKeys.Value.Keys) { PrintItem(key); } } request.RequestItems = unprocessedKeys; } while (response.UnprocessedKeys.Count > 0); } private static void PrintItem(Dictionary<string, AttributeValue> attributeList) { foreach (KeyValuePair<string, AttributeValue> kvp in attributeList) { string attributeName = kvp.Key; AttributeValue value = kvp.Value; Console.WriteLine( attributeName + " " + (value.S == null ? "" : "S=[" + value.S + "]") + (value.N == null ? "" : "N=[" + value.N + "]") + (value.SS == null ? "" : "SS=[" + string.Join(",", value.SS.ToArray()) + "]") + (value.NS == null ? "" : "NS=[" + string.Join(",", value.NS.ToArray()) + "]") ); } Console.WriteLine("************************************************"); } } }