AWS SDK for .NET의 Table.Query 메서드 - Amazon DynamoDB

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

AWS SDK for .NET의 Table.Query 메서드

Query 메서드를 사용하면 테이블을 쿼리할 수 있습니다. 복합 기본 키(파티션 키 및 정렬 키)가 있는 테이블만 쿼리할 수 있습니다. 테이블의 기본 키가 파티션 키로만 구성된 경우에는 Query 작업이 지원되지 않습니다. 기본적으로 Query는 최종적으로 일관적인 쿼리를 내부적으로 수행합니다. 일관성 모델에 대한 자세한 내용은 읽기 정합성를 참조하세요.

Query 메서드는 두 개의 오버로드를 제공합니다. Query 메서드에 대한 최소 필수 파라미터는 파티션 키 값과 정렬 키 필터입니다. 다음 오버로드를 사용하여 이러한 최소 필수 파라미터를 제공할 수 있습니다.

Query(Primitive partitionKey, RangeFilter Filter);

예를 들어, 다음 C# 코드에서는 지난 15일 간 게시된 모든 포럼 회신에 쿼리합니다.

string tableName = "Reply"; Table table = Table.LoadTable(client, tableName); DateTime twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15); RangeFilter filter = new RangeFilter(QueryOperator.GreaterThan, twoWeeksAgoDate); Search search = table.Query("DynamoDB Thread 2", filter);

이는 Search 객체를 만듭니다. 이제 다음 C# 코드 예제와 같이 Search.GetNextSet 메서드를 반복적으로 호출하여 한 번에 결과 페이지 하나를 검색할 수 있습니다. 이 코드는 쿼리에서 반환하는 각 항목에 대한 속성 값을 인쇄합니다.

List<Document> documentSet = new List<Document>(); do { documentSet = search.GetNextSet(); foreach (var document in documentSet) PrintDocument(document); } while (!search.IsDone); private static void PrintDocument(Document document) { Console.WriteLine(); foreach (var attribute in document.GetAttributeNames()) { string stringValue = null; var value = document[attribute]; if (value is Primitive) stringValue = value.AsPrimitive().Value; else if (value is PrimitiveList) stringValue = string.Join(",", (from primitive in value.AsPrimitiveList().Entries select primitive.Value).ToArray()); Console.WriteLine("{0} - {1}", attribute, stringValue); } }

옵션 파라미터 지정

가져올 속성 목록, strongly consistent read, 페이지 크기 및 페이지당 반환된 항목 수를 지정하는 등 Query에 대한 선택적 파라미터를 지정할 수도 있습니다. 파라미터의 전체 목록은 Query 단원을 참조하세요. 선택적 파라미터를 지정하려면 QueryOperationConfig 객체를 제공하는 다음과 같은 오버로드를 사용해야 합니다.

Query(QueryOperationConfig config);

앞 예의 쿼리를 실행한다고 가정하겠습니다(지난 15일간 게시한 포럼 회신 가져오기). 그러나 선택적 쿼리 파라미터를 제공하여 특정 속성만 가져오고 또한 강력한 일관된 읽기(Strongly Consistent Read)를 요청한다고 가정합니다. 다음 C# 코드 예제에서는 QueryOperationConfig 객체를 사용하여 요청을 구성합니다.

Table table = Table.LoadTable(client, "Reply"); DateTime twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15); QueryOperationConfig config = new QueryOperationConfig() { HashKey = "DynamoDB Thread 2", //Partition key AttributesToGet = new List<string> { "Subject", "ReplyDateTime", "PostedBy" }, ConsistentRead = true, Filter = new RangeFilter(QueryOperator.GreaterThan, twoWeeksAgoDate) }; Search search = table.Query(config);

예: Table.Query 메서드를 사용하여 쿼리

다음 C# 코드 예제에서는 Table.Query 메서드를 사용하여 다음 샘플 쿼리를 실행합니다.

  • 다음 쿼리는 Reply 테이블에 대해 실행됩니다.

    • 지난 15일간 게시된 포럼 스레드 회신을 찾습니다.

      이 쿼리는 두 번 실행됩니다. 첫 번째 Table.Query 호출에서 이 예제는 필수 쿼리 파라미터만 제공합니다. 두 번째 Table.Query 호출에서는 선택적 쿼리 파라미터를 제공하여 강력히 일관된 읽기 및 검색할 속성 목록을 요청합니다.

    • 일정 기간 동안 게시된 포럼 스레드 회신을 찾습니다.

      이 쿼리는 Between 쿼리 연산자를 사용하여 두 날짜 사이에 게시된 회신을 찾습니다.

  • ProductCatalog 테이블에서 제품을 가져옵니다.

    ProductCatalog 테이블의 기본 키는 파티션 키로만 구성되어 있으므로 항목만 가져올 수 있고, 테이블을 쿼리할 수는 없습니다. 이 예제에서는 항목 Id를 사용하여 특정 제품 항목을 검색합니다.

using System; using System.Collections.Generic; using System.Linq; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DocumentModel; using Amazon.Runtime; using Amazon.SecurityToken; namespace com.amazonaws.codesamples { class MidLevelQueryAndScan { private static AmazonDynamoDBClient client = new AmazonDynamoDBClient(); static void Main(string[] args) { try { // Query examples. Table replyTable = Table.LoadTable(client, "Reply"); string forumName = "Amazon DynamoDB"; string threadSubject = "DynamoDB Thread 2"; FindRepliesInLast15Days(replyTable, forumName, threadSubject); FindRepliesInLast15DaysWithConfig(replyTable, forumName, threadSubject); FindRepliesPostedWithinTimePeriod(replyTable, forumName, threadSubject); // Get Example. Table productCatalogTable = Table.LoadTable(client, "ProductCatalog"); int productId = 101; GetProduct(productCatalogTable, productId); Console.WriteLine("To continue, press Enter"); Console.ReadLine(); } catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); } catch (AmazonServiceException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } } private static void GetProduct(Table tableName, int productId) { Console.WriteLine("*** Executing GetProduct() ***"); Document productDocument = tableName.GetItem(productId); if (productDocument != null) { PrintDocument(productDocument); } else { Console.WriteLine("Error: product " + productId + " does not exist"); } } private static void FindRepliesInLast15Days(Table table, string forumName, string threadSubject) { string Attribute = forumName + "#" + threadSubject; DateTime twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15); QueryFilter filter = new QueryFilter("Id", QueryOperator.Equal, partitionKey); filter.AddCondition("ReplyDateTime", QueryOperator.GreaterThan, twoWeeksAgoDate); // Use Query overloads that takes the minimum required query parameters. Search search = table.Query(filter); List<Document> documentSet = new List<Document>(); do { documentSet = search.GetNextSet(); Console.WriteLine("\nFindRepliesInLast15Days: printing ............"); foreach (var document in documentSet) PrintDocument(document); } while (!search.IsDone); } private static void FindRepliesPostedWithinTimePeriod(Table table, string forumName, string threadSubject) { DateTime startDate = DateTime.UtcNow.Subtract(new TimeSpan(21, 0, 0, 0)); DateTime endDate = DateTime.UtcNow.Subtract(new TimeSpan(1, 0, 0, 0)); QueryFilter filter = new QueryFilter("Id", QueryOperator.Equal, forumName + "#" + threadSubject); filter.AddCondition("ReplyDateTime", QueryOperator.Between, startDate, endDate); QueryOperationConfig config = new QueryOperationConfig() { Limit = 2, // 2 items/page. Select = SelectValues.SpecificAttributes, AttributesToGet = new List<string> { "Message", "ReplyDateTime", "PostedBy" }, ConsistentRead = true, Filter = filter }; Search search = table.Query(config); List<Document> documentList = new List<Document>(); do { documentList = search.GetNextSet(); Console.WriteLine("\nFindRepliesPostedWithinTimePeriod: printing replies posted within dates: {0} and {1} ............", startDate, endDate); foreach (var document in documentList) { PrintDocument(document); } } while (!search.IsDone); } private static void FindRepliesInLast15DaysWithConfig(Table table, string forumName, string threadName) { DateTime twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15); QueryFilter filter = new QueryFilter("Id", QueryOperator.Equal, forumName + "#" + threadName); filter.AddCondition("ReplyDateTime", QueryOperator.GreaterThan, twoWeeksAgoDate); // You are specifying optional parameters so use QueryOperationConfig. QueryOperationConfig config = new QueryOperationConfig() { Filter = filter, // Optional parameters. Select = SelectValues.SpecificAttributes, AttributesToGet = new List<string> { "Message", "ReplyDateTime", "PostedBy" }, ConsistentRead = true }; Search search = table.Query(config); List<Document> documentSet = new List<Document>(); do { documentSet = search.GetNextSet(); Console.WriteLine("\nFindRepliesInLast15DaysWithConfig: printing ............"); foreach (var document in documentSet) PrintDocument(document); } while (!search.IsDone); } private static void PrintDocument(Document document) { // count++; Console.WriteLine(); foreach (var attribute in document.GetAttributeNames()) { string stringValue = null; var value = document[attribute]; if (value is Primitive) stringValue = value.AsPrimitive().Value.ToString(); else if (value is PrimitiveList) stringValue = string.Join(",", (from primitive in value.AsPrimitiveList().Entries select primitive.Value).ToArray()); Console.WriteLine("{0} - {1}", attribute, stringValue); } } } }