항목 작업: .NET - Amazon DynamoDB

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

항목 작업: .NET

AWS SDK for .NET 하위 수준 API를 사용하여 테이블 항목에 대한 생성, 읽기, 업데이트, 삭제 작업(CRUD)을 수행할 수 있습니다. 다음은 .NET 하위 수준 API를 사용하여 데이터 CRUD를 작업할 때 따라야 할 공통 단계입니다.

  1. AmazonDynamoDBClient 클래스(클라이언트)의 인스턴스를 만듭니다.

  2. 각 요청 객체에서 작업에 따라 필요한 파라미터를 입력합니다.

    예를 들어 항목을 업로드할 때는 PutItemRequest 요청 객체를 사용하고, 기존 항목을 가져올 때는 GetItemRequest 요청 객체를 사용합니다.

    요청 객체를 사용하여 필수 파라미터와 옵션 파라미터를 모두 입력할 수도 있습니다.

  3. 이전 단계에서 생성한 요청 객체를 전달하여 클라이언트 제공 메서드를 실행합니다.

    CRUD 작업을 위해 AmazonDynamoDBClient 클라이언트가 제공하는 메서드는 PutItem, GetItem, UpdateItemDeleteItem입니다.

항목 추가

PutItem 메서드는 항목을 테이블에 업로드합니다. 항목이 존재하는 경우 전체 항목을 바꿉니다.

참고

전체 항목을 변경하지 않고 특정 속성만 업데이트하는 경우에는 UpdateItem 메서드를 사용하면 됩니다. 자세한 설명은 항목 업데이트 섹션을 참조하세요.

다음은 하위 수준 .NET SDK API를 사용하여 항목을 업로드하는 단계입니다.

  1. AmazonDynamoDBClient 클래스의 인스턴스를 만듭니다.

  2. PutItemRequest 클래스 인스턴스를 생성하여 필요한 파라미터를 입력합니다.

    항목을 업로드하려면 테이블 이름과 항목을 입력해야 합니다.

  3. 이전 단계에서 생성한 PutItemRequest 객체를 입력하여 PutItem 메서드를 실행합니다.

다음 C# 예제에서는 이전 단계를 설명합니다. 이 예제에서는 항목을 ProductCatalog 테이블에 업로드합니다.

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new PutItemRequest { TableName = tableName, Item = new Dictionary<string, AttributeValue>() { { "Id", new AttributeValue { N = "201" }}, { "Title", new AttributeValue { S = "Book 201 Title" }}, { "ISBN", new AttributeValue { S = "11-11-11-11" }}, { "Price", new AttributeValue { S = "20.00" }}, { "Authors", new AttributeValue { SS = new List<string>{"Author1", "Author2"} } } } }; client.PutItem(request);

위 예제에서 업로드한 book 항목에는 Id, Title, ISBNAuthors 속성이 있습니다. Id는 숫자 형식의 속성이고, 나머지 모든 속성들은 문자열 형식입니다. 작성자는 String 집합입니다.

옵션 파라미터 지정

아래 C# 예제에서와 같이 PutItemRequest 객체를 사용하여 옵션 파라미터를 지정할 수도 있습니다. 이 예제에서 지정하는 옵션 파라미터는 다음과 같습니다.

  • ExpressionAttributeNames, ExpressionAttributeValuesConditionExpression 파라미터는 기존 항목에 특정 값의 ISBN 속성이 있는 경우에 한해 항목을 변경할 수 있도록 지정합니다.

  • ReturnValues 파라미터는 응답 시 이전 항목을 요청합니다.

var request = new PutItemRequest { TableName = tableName, Item = new Dictionary<string, AttributeValue>() { { "Id", new AttributeValue { N = "104" }}, { "Title", new AttributeValue { S = "Book 104 Title" }}, { "ISBN", new AttributeValue { S = "444-4444444444" }}, { "Authors", new AttributeValue { SS = new List<string>{"Author3"}}} }, // Optional parameters. ExpressionAttributeNames = new Dictionary<string,string>() { {"#I", "ISBN"} }, ExpressionAttributeValues = new Dictionary<string, AttributeValue>() { {":isbn",new AttributeValue {S = "444-4444444444"}} }, ConditionExpression = "#I = :isbn" }; var response = client.PutItem(request);

자세한 내용은 을 참조하십시오 PutItem.

항목 가져오기

GetItem 메서드는 항목을 가져옵니다.

참고

다수의 항목을 가져올 때는 BatchGetItem 메서드를 사용합니다. 자세한 설명은 일괄 가져오기: 여러 항목 가져오기 섹션을 참조하세요.

다음은 하위 수준 AWS SDK for .NET API를 사용하여 기존 항목을 가져오는 단계입니다.

  1. AmazonDynamoDBClient 클래스의 인스턴스를 만듭니다.

  2. GetItemRequest 클래스 인스턴스를 생성하여 필요한 파라미터를 입력합니다.

    항목을 가져오려면 테이블 이름과 항목의 기본 키를 입력해야 합니다.

  3. 이전 단계에서 생성한 GetItemRequest 객체를 입력하여 GetItem 메서드를 실행합니다.

다음 C# 예제에서는 이전 단계를 설명합니다. 이 예제에서는 ProductCatalog 테이블에서 항목을 검색합니다.

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new GetItemRequest { TableName = tableName, Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } }, }; var response = client.GetItem(request); // Check the response. var result = response.GetItemResult; var attributeMap = result.Item; // Attribute list in the response.

옵션 파라미터 지정

아래 C# 예제에서와 같이 GetItemRequest 객체를 사용하여 옵션 파라미터를 지정할 수도 있습니다. 이 샘플에서 지정하는 옵션 파라미터는 다음과 같습니다.

  • ProjectionExpression 파라미터는 가져올 속성을 지정합니다.

  • ConsistentRead 파라미터는 Strongly Consistent Read를 실행합니다. 읽기 일관성에 대한 자세한 내용은 읽기 정합성 단원을 참조하십시오.

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new GetItemRequest { TableName = tableName, Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } }, // Optional parameters. ProjectionExpression = "Id, ISBN, Title, Authors", ConsistentRead = true }; var response = client.GetItem(request); // Check the response. var result = response.GetItemResult; var attributeMap = result.Item;

자세한 내용은 을 참조하십시오 GetItem.

항목 업데이트

UpdateItem 메서드는 기존 항목이 있는 경우 이를 업데이트합니다. UpdateItem 작업을 사용하면 기존 속성 값을 업데이트하거나, 새로운 속성을 추가하거나, 혹은 기존 속성 컬렉션에서 속성을 삭제할 수도 있습니다. 기본 키를 지정한 항목이 없는 경우에는 새로운 항목을 추가합니다.

UpdateItem 작업은 다음 지침을 사용합니다.

  • 항목이 없는 경우 UpdateItem은 입력에서 지정한 기본 키를 사용하여 새 항목을 추가합니다.

  • 항목이 있는 경우 UpdateItem은 다음과 같이 업데이트를 적용합니다.

    • 기존 속성 값을 업데이트 값으로 변경합니다.

    • 입력한 속성이 없는 경우에는 새로운 속성을 항목에 추가합니다.

    • 입력 속성이 null인 경우에는 입력한 속성이 있으면 삭제합니다.

    • Action에서 ADD를 사용하면 기존 집합(문자열 또는 숫자 집합)에 값을 추가하거나, 기존 숫자 속성 값에서 수치적으로 더하거나(양수 사용) 뺄 수 있습니다(음수 사용).

참고

PutItem 작업은 업데이트도 가능합니다. 자세한 설명은 항목 추가 섹션을 참조하세요. 예를 들어 PutItem을 호출하여 항목을 업데이트할 때 기본 키가 있을 경우 PutItem 작업이 전체 항목을 변경합니다. 기존 항목에 속성이 있으나 그러한 속성이 입력에 지정되지 않은 경우, PutItem 작업은 그러한 속성을 삭제합니다. 그러나 UpdateItem은 지정된 입력 속성만 업데이트합니다. 해당 항목의 다른 모든 기존 속성은 변경되지 않고 그대로 유지됩니다.

다음은 하위 수준 .NET SDK API를 사용하여 기존 항목을 업데이트하는 단계입니다.

  1. AmazonDynamoDBClient 클래스의 인스턴스를 만듭니다.

  2. UpdateItemRequest 클래스 인스턴스를 생성하여 필요한 파라미터를 입력합니다.

    이 인스턴스는 속성 추가, 기존 속성 업데이트 또는 속성 삭제 등과 같이 모든 업데이트를 설명하는 요청 객체입니다. 기존 속성을 삭제하려면 null 값으로 속성 이름을 지정합니다.

  3. 이전 단계에서 생성한 UpdateItemRequest 객체를 입력하여 UpdateItem 메서드를 실행합니다.

다음 C# 코드 예제에서는 이전 단계를 설명합니다. 이 예제에서는 ProductCatalog 테이블의 book 항목을 업데이트합니다. 새로운 작성자를 Authors 컬렉션에 추가하고 기존 ISBN 속성을 삭제합니다. 또한 가격을 1만큼 내립니다.

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new UpdateItemRequest { TableName = tableName, Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } }, ExpressionAttributeNames = new Dictionary<string,string>() { {"#A", "Authors"}, {"#P", "Price"}, {"#NA", "NewAttribute"}, {"#I", "ISBN"} }, ExpressionAttributeValues = new Dictionary<string, AttributeValue>() { {":auth",new AttributeValue { SS = {"Author YY","Author ZZ"}}}, {":p",new AttributeValue {N = "1"}}, {":newattr",new AttributeValue {S = "someValue"}}, }, // This expression does the following: // 1) Adds two new authors to the list // 2) Reduces the price // 3) Adds a new attribute to the item // 4) Removes the ISBN attribute from the item UpdateExpression = "ADD #A :auth SET #P = #P - :p, #NA = :newattr REMOVE #I" }; var response = client.UpdateItem(request);

옵션 파라미터 지정

아래 C# 예제에서와 같이 UpdateItemRequest 객체를 사용하여 옵션 파라미터를 지정할 수도 있습니다. 이 예제에서 지정하는 옵션 파라미터는 다음과 같습니다.

  • ExpressionAttributeValuesConditionExpression 파라미터는 기존 가격이 20.00인 경우에만 가격을 업데이트하도록 지정합니다.

  • ReturnValues 파라미터는 응답 시 업데이트된 항목을 요청합니다.

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new UpdateItemRequest { Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } }, // Update price only if the current price is 20.00. ExpressionAttributeNames = new Dictionary<string,string>() { {"#P", "Price"} }, ExpressionAttributeValues = new Dictionary<string, AttributeValue>() { {":newprice",new AttributeValue {N = "22"}}, {":currprice",new AttributeValue {N = "20"}} }, UpdateExpression = "SET #P = :newprice", ConditionExpression = "#P = :currprice", TableName = tableName, ReturnValues = "ALL_NEW" // Return all the attributes of the updated item. }; var response = client.UpdateItem(request);

자세한 내용은 을 참조하십시오 UpdateItem.

원자성 카운터

updateItem을 사용하여 원자성 카운터를 구현할 수 있습니다. 이는 다른 쓰기 요청과 충돌하지 않고도 기존 속성의 값을 증감합니다. 원자성 카운터를 업데이트하려면 UpdateExpression 파라미터에서 Number 형식의 속성을 가진 updateItem을 사용하고, ADD에서는 Action을 사용합니다.

다음 예제는 Quantity 속성을 하나씩 늘리며 이를 보여 줍니다.

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new UpdateItemRequest { Key = new Dictionary<string, AttributeValue>() { { "Id", new AttributeValue { N = "121" } } }, ExpressionAttributeNames = new Dictionary<string, string>() { {"#Q", "Quantity"} }, ExpressionAttributeValues = new Dictionary<string, AttributeValue>() { {":incr",new AttributeValue {N = "1"}} }, UpdateExpression = "SET #Q = #Q + :incr", TableName = tableName }; var response = client.UpdateItem(request);

항목 삭제

DeleteItem 메서드는 테이블에서 항목을 삭제합니다.

다음은 하위 수준 .NET SDK API를 사용하여 항목을 삭제하는 단계입니다.

  1. AmazonDynamoDBClient 클래스의 인스턴스를 만듭니다.

  2. DeleteItemRequest 클래스 인스턴스를 생성하여 필요한 파라미터를 입력합니다.

    항목을 삭제하려면 테이블 이름과 항목의 기본 키가 필요합니다.

  3. 이전 단계에서 생성한 DeleteItemRequest 객체를 입력하여 DeleteItem 메서드를 실행합니다.

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new DeleteItemRequest { TableName = tableName, Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "201" } } }, }; var response = client.DeleteItem(request);

옵션 파라미터 지정

아래 C# 코드 예제에서와 같이 DeleteItemRequest 객체를 사용하여 옵션 파라미터를 지정할 수도 있습니다. 이 예제에서 지정하는 옵션 파라미터는 다음과 같습니다.

  • ExpressionAttributeValues책 항목이 더 이상 출판되지 않는 경우에만 삭제할 수 ConditionExpression 있도록 지정할 수도 있습니다 ( InPublication 속성 값은 false).

  • ReturnValues 파라미터는 응답 시 삭제된 항목을 요청합니다.

var request = new DeleteItemRequest { TableName = tableName, Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "201" } } }, // Optional parameters. ReturnValues = "ALL_OLD", ExpressionAttributeNames = new Dictionary<string, string>() { {"#IP", "InPublication"} }, ExpressionAttributeValues = new Dictionary<string, AttributeValue>() { {":inpub",new AttributeValue {BOOL = false}} }, ConditionExpression = "#IP = :inpub" }; var response = client.DeleteItem(request);

자세한 내용은 을 참조하십시오 DeleteItem.

일괄 쓰기 - 여러 항목 추가 및 삭제

배치 쓰기란 다수의 항목을 배치로 입력 및 삭제하는 것을 말합니다. BatchWriteItem 메서드를 사용하면 단 한 번의 호출로 하나 이상의 테이블에 다수의 항목을 업로드하거나 삭제할 수 있습니다. 다음은 하위 수준 .NET SDK API를 사용하여 다수의 항목을 가져오는 단계입니다.

  1. AmazonDynamoDBClient 클래스의 인스턴스를 만듭니다.

  2. BatchWriteItemRequest 클래스 인스턴스를 생성하여 모든 업로드 및 삭제 작업을 설명합니다.

  3. 이전 단계에서 생성한 BatchWriteItemRequest 객체를 입력하여 BatchWriteItem 메서드를 실행합니다.

  4. 응답을 처리합니다. 응답과 함께 반환되는 요청 항목 중 처리하지 않은 항목이 있는지 확인해야 합니다. 프로비저닝된 처리량이 할당량에 이르거나 일시적 오류가 발생하면 이러한 경우가 발생할 수 있습니다. 또한 DynamoDB는 요청 시 지정하는 요청 크기나 작업 수를 제한합니다. 따라서 이러한 제한을 초과할 경우 DynamoDB가 요청을 거부하기도 합니다. 자세한 내용은 을 참조하십시오 BatchWriteItem.

다음 C# 코드 예제에서는 이전 단계를 설명합니다. 아래 예제는 BatchWriteItemRequest를 생성하여 다음 쓰기 작업을 실행합니다.

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

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

그런 다음 코드가 BatchWriteItem을 실행하여 배치 작업을 시작합니다.

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string table1Name = "Forum"; string table2Name = "Thread"; var request = new BatchWriteItemRequest { RequestItems = new Dictionary<string, List<WriteRequest>> { { table1Name, new List<WriteRequest> { new WriteRequest { PutRequest = new PutRequest { Item = new Dictionary<string,AttributeValue> { { "Name", new AttributeValue { S = "Amazon 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 = "Amazon S3 forum" } }, { "Subject", new AttributeValue { S = "My sample question" } }, { "Message", new AttributeValue { S = "Message Text." } }, { "KeywordTags", new AttributeValue { SS = new List<string> { "Amazon S3", "Bucket" } } } } } }, new WriteRequest { DeleteRequest = new DeleteRequest { Key = new Dictionary<string,AttributeValue>() { { "ForumName", new AttributeValue { S = "Some forum name" } }, { "Subject", new AttributeValue { S = "Some subject" } } } } } } } } }; response = client.BatchWriteItem(request);

사용 가능한 예제는 예: AWS SDK for .NET 하위 수준 API를 사용하는 일괄 작업를 참조하세요.

일괄 가져오기: 여러 항목 가져오기

BatchGetItem 메서드를 사용하면 하나 이상의 테이블에서 여러 항목을 검색할 수 있습니다.

참고

단일 항목을 검색하려면 GetItem 메서드를 사용합니다.

다음은 하위 수준 AWS SDK for .NET API를 사용하여 다수의 항목을 가져오는 단계입니다.

  1. AmazonDynamoDBClient 클래스의 인스턴스를 만듭니다.

  2. BatchGetItemRequest 클래스 인스턴스를 생성하여 필요한 파라미터를 입력합니다.

    다수의 항목을 가져오려면 테이블 이름과 기본 키 값의 목록이 필요합니다.

  3. 이전 단계에서 생성한 BatchGetItemRequest 객체를 입력하여 BatchGetItem 메서드를 실행합니다.

  4. 응답을 처리합니다. 처리하지 않은 키가 있는지 확인해야 합니다. 프로비저닝된 처리량이 할당량에 이르거나 일시적 오류가 발생하면 이러한 경우가 발생할 수 있습니다.

다음 C# 코드 예제에서는 이전 단계를 설명합니다. 아래 예제에서는 ForumThread 테이블에서 항목을 가져옵니다. 요청에 따라 지정하는 항목 수는 Forum 테이블에서 2개, 그리고 Thread 테이블에서 3개입니다. 따라서 이 요청에는 두 테이블의 항목이 모두 포함됩니다. 코드를 보면 응답의 처리 방식을 알 수 있습니다.

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string table1Name = "Forum"; string table2Name = "Thread"; 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 = "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 = "DynamoDB" } }, { "Subject", new AttributeValue { S = "DynamoDB Thread 1" } } }, new Dictionary<string, AttributeValue>() { { "ForumName", new AttributeValue { S = "DynamoDB" } }, { "Subject", new AttributeValue { S = "DynamoDB Thread 2" } } }, new Dictionary<string, AttributeValue>() { { "ForumName", new AttributeValue { S = "Amazon S3" } }, { "Subject", new AttributeValue { S = "Amazon S3 Thread 1" } } } } } } } }; var response = client.BatchGetItem(request); // Check the response. var result = response.BatchGetItemResult; var responses = result.Responses; // The attribute list in the response. var table1Results = responses[table1Name]; Console.WriteLine("Items in table {0}" + table1Name); foreach (var item1 in table1Results.Items) { PrintItem(item1); } var table2Results = responses[table2Name]; Console.WriteLine("Items in table {1}" + table2Name); foreach (var item2 in table2Results.Items) { PrintItem(item2); } // Any unprocessed keys? could happen if you exceed ProvisionedThroughput or some other error. Dictionary<string, KeysAndAttributes> unprocessedKeys = result.UnprocessedKeys; foreach (KeyValuePair<string, KeysAndAttributes> pair in unprocessedKeys) { Console.WriteLine(pair.Key, pair.Value); }

옵션 파라미터 지정

아래 C# 코드 예제에서와 같이 BatchGetItemRequest 객체를 사용하여 옵션 파라미터를 지정할 수도 있습니다. 이 예제에서는 Forum 테이블에서 두 개의 항목을 가져옵니다. 이 예제에서 지정하는 옵션 파라미터는 다음과 같습니다.

  • ProjectionExpression 파라미터는 가져올 속성을 지정합니다.

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string table1Name = "Forum"; 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 = "DynamoDB" } } }, new Dictionary<string, AttributeValue>() { { "Name", new AttributeValue { S = "Amazon S3" } } } } }, // Optional - name of an attribute to retrieve. ProjectionExpression = "Title" } } }; var response = client.BatchGetItem(request);

자세한 내용은 을 참조하십시오 BatchGetItem.