例: AWS SDK for .NET のオブジェクト永続性モデルを使用した、DynamoDB でのクエリおよびスキャン
このセクションの C# コード例では、次のクラスを定義して、DynamoDB 内のテーブルにマッピングしています。この例で使用されているテーブルの作成については、「DynamoDB でのコード例用のテーブルの作成とデータのロード」を参照してください。
-
Book
クラスは、ProductCatalog
テーブルにマッピングされます。 -
Forum
、Thread
、およびReply
クラスは、同じ名前のテーブルにマッピングされます。
この例では DynamoDBContext
を使用して、さらに次のクエリとスキャンオペレーションを実行しています。
-
Id
によって書籍を取得します。ProductCatalog
テーブルには、プライマリキーとしてId
があります。プライマリキーの一部にソートキーは含まれていません。したがって、テーブルのクエリを行うことはできません。項目はId
値を使用して取得できます。 -
Reply
テーブルに対して次のクエリを実行します。(Reply
テーブルのプライマリキーには、Id
およびReplyDateTime
属性が含まれます。ReplyDateTime
はソートキーで、これによりテーブルのクエリが実行されます。)-
過去 15 日間に投稿されたフォーラムスレッドに対する返信を検索します。
-
特定の日付範囲の間に投稿されたフォーラムスレッドに対する返信を検索します。
-
-
ProductCatalog
テーブルをスキャンし、価格が 0 以下の書籍を検索します。パフォーマンス上の理由から、スキャンオペレーションではなくクエリオペレーションを使用するようにしてください。ただし、場合によってはテーブルをスキャンする必要があります。データ入力エラーがあり、書籍の価格の 1 つが 0 未満に設定されたとします。この例では、
ProductCategory
テーブルをスキャンして、価格が 0 未満である書籍項目 (ProductCategory
は書籍) を検索しています。
実例を作成する方法については、「.NET コード例」を参照してください。
注記
以下の例は、同期メソッドをサポートしていないため、.NET Core コアには適用されません。詳細については、「.NET 用 AWS 非同期 API」を参照してください。
例
/** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ 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; } } }