예: AWS SDK for .NET 객체 지속성 모델을 사용하여 DynamoDB에서 쿼리 및 스캔 - Amazon DynamoDB

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

예: AWS SDK for .NET 객체 지속성 모델을 사용하여 DynamoDB에서 쿼리 및 스캔

이 섹션의 C# 예제는 다음 클래스를 정의하여 DynamoDB의 테이블에 매핑합니다. 이번 예제에 사용된 테이블 생성에 대한 자세한 내용은 DynamoDB에서 테이블 생성 및 코드 예시에 대한 데이터 로드 단원을 참조하세요.

  • Book 클래스가 ProductCatalog 테이블로 매핑됩니다.

  • Forum, ThreadReply 클래스가 동일한 이름의 테이블로 매핑됩니다.

그런 다음 이 예제는 DynamoDBContext를 사용하여 다음의 쿼리 및 스캔 작업을 실행합니다.

  • Id로 책을 가져옵니다.

    ProductCatalog 테이블에 기본 키로 Id가 있습니다. 정렬 키는 기본 키에 포함되어 있지 않습니다. 따라서 테이블에 대한 쿼리는 실행할 수 없습니다. 해당 Id 값을 사용하여 항목을 가져올 수 있습니다.

  • Reply 테이블에 대해 다음 쿼리를 실행합니다. (Reply 테이블의 기본 키는 IdReplyDateTime 속성으로 구성됩니다. ReplyDateTime은 정렬 키이므로 이 테이블을 쿼리할 수 있습니다.)

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

    • 특정 기간 게시된 포럼 스레드의 댓글을 찾습니다.

  • ProductCatalog 테이블을 스캔하여 가격이 0보다 작은 책을 찾습니다.

    성능 문제 때문에 스캔 작업 대신 쿼리 작업을 사용해야 합니다. 하지만 테이블 스캔이 필요할 때도 있습니다. 데이터 입력 오류가 있으며 책 가격이 0 미만으로 설정되어 있는 경우 이 예제는 ProductCategory 테이블을 스캔하여 가격이 0 미만인 책 항목(ProductCategory = 책)을 찾습니다.

실제 예제를 작성하는 방법은 .NET 코드 예시 단원을 참조하세요.

참고

다음 예제는 동기식 메서드를 지원하지 않으므로 .NET core에서 작동되지 않습니다. 자세한 내용은 .NET용 AWS 비동기식 API를 참조하세요.

using System; using System.Collections.Generic; using System.Configuration; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; using Amazon.DynamoDBv2.DocumentModel; using Amazon.Runtime; namespace com.amazonaws.codesamples { class HighLevelQueryAndScan { private static AmazonDynamoDBClient client = new AmazonDynamoDBClient(); static void Main(string[] args) { try { DynamoDBContext context = new DynamoDBContext(client); // Get an item. GetBook(context, 101); // Sample forum and thread to test queries. string forumName = "Amazon DynamoDB"; string threadSubject = "DynamoDB Thread 1"; // Sample queries. FindRepliesInLast15Days(context, forumName, threadSubject); FindRepliesPostedWithinTimePeriod(context, forumName, threadSubject); // Scan table. FindProductsPricedLessThanZero(context); 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 GetBook(DynamoDBContext context, int productId) { Book bookItem = context.Load<Book>(productId); Console.WriteLine("\nGetBook: Printing result....."); Console.WriteLine("Title: {0} \n No.Of threads:{1} \n No. of messages: {2}", bookItem.Title, bookItem.ISBN, bookItem.PageCount); } private static void FindRepliesInLast15Days(DynamoDBContext context, string forumName, string threadSubject) { string replyId = forumName + "#" + threadSubject; DateTime twoWeeksAgoDate = DateTime.UtcNow - TimeSpan.FromDays(15); IEnumerable<Reply> latestReplies = context.Query<Reply>(replyId, QueryOperator.GreaterThan, twoWeeksAgoDate); Console.WriteLine("\nFindRepliesInLast15Days: Printing result....."); foreach (Reply r in latestReplies) Console.WriteLine("{0}\t{1}\t{2}\t{3}", r.Id, r.PostedBy, r.Message, r.ReplyDateTime); } private static void FindRepliesPostedWithinTimePeriod(DynamoDBContext context, string forumName, string threadSubject) { string forumId = forumName + "#" + threadSubject; Console.WriteLine("\nFindRepliesPostedWithinTimePeriod: Printing result....."); DateTime startDate = DateTime.UtcNow - TimeSpan.FromDays(30); DateTime endDate = DateTime.UtcNow - TimeSpan.FromDays(1); IEnumerable<Reply> repliesInAPeriod = context.Query<Reply>(forumId, QueryOperator.Between, startDate, endDate); foreach (Reply r in repliesInAPeriod) Console.WriteLine("{0}\t{1}\t{2}\t{3}", r.Id, r.PostedBy, r.Message, r.ReplyDateTime); } private static void FindProductsPricedLessThanZero(DynamoDBContext context) { int price = 0; IEnumerable<Book> itemsWithWrongPrice = context.Scan<Book>( new ScanCondition("Price", ScanOperator.LessThan, price), new ScanCondition("ProductCategory", ScanOperator.Equal, "Book") ); Console.WriteLine("\nFindProductsPricedLessThanZero: Printing result....."); foreach (Book r in itemsWithWrongPrice) Console.WriteLine("{0}\t{1}\t{2}\t{3}", r.Id, r.Title, r.Price, r.ISBN); } } [DynamoDBTable("Reply")] public class Reply { [DynamoDBHashKey] //Partition key public string Id { get; set; } [DynamoDBRangeKey] //Sort key public DateTime ReplyDateTime { get; set; } // Properties included implicitly. public string Message { get; set; } // Explicit property mapping with object persistence model attributes. [DynamoDBProperty("LastPostedBy")] public string PostedBy { get; set; } // Property to store version number for optimistic locking. [DynamoDBVersion] public int? Version { get; set; } } [DynamoDBTable("Thread")] public class Thread { // Partition key mapping. [DynamoDBHashKey] //Partition key public string ForumName { get; set; } [DynamoDBRangeKey] //Sort key public DateTime Subject { get; set; } // Implicit mapping. public string Message { get; set; } public string LastPostedBy { get; set; } public int Views { get; set; } public int Replies { get; set; } public bool Answered { get; set; } public DateTime LastPostedDateTime { get; set; } // Explicit mapping (property and table attribute names are different). [DynamoDBProperty("Tags")] public List<string> KeywordTags { get; set; } // Property to store version number for optimistic locking. [DynamoDBVersion] public int? Version { get; set; } } [DynamoDBTable("Forum")] public class Forum { [DynamoDBHashKey] public string Name { get; set; } // All the following properties are explicitly mapped // to show how to provide mapping. [DynamoDBProperty] public int Threads { get; set; } [DynamoDBProperty] public int Views { get; set; } [DynamoDBProperty] public string LastPostBy { get; set; } [DynamoDBProperty] public DateTime LastPostDateTime { get; set; } [DynamoDBProperty] public int Messages { get; set; } } [DynamoDBTable("ProductCatalog")] public class Book { [DynamoDBHashKey] //Partition key public int Id { get; set; } public string Title { get; set; } public string ISBN { get; set; } public int Price { get; set; } public string PageCount { get; set; } public string ProductCategory { get; set; } public bool InPublication { get; set; } } }