Esempio: query e scansione in DynamoDB utilizzando il modello di persistenza degli oggetti di AWS SDK for .NET - Amazon DynamoDB

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Esempio: query e scansione in DynamoDB utilizzando il modello di persistenza degli oggetti di AWS SDK for .NET

Nell'esempio C# di questa sezione vengono definite le seguenti classi, le quali vengono mappate alle tabelle di DynamoDB. Per ulteriori informazioni sulla creazione delle tabelle utilizzate in questo esempio, consulta Creazione di tabelle e caricamento di dati per esempi di codice in DynamoDB.

  • La classe Book viene mappata alla tabella ProductCatalog.

  • Le classi Forum, Thread e Reply vengono mappate alle tabelle con lo stesso nome.

In questo esempio vengono poi eseguite le seguenti operazioni di query e di scansione utilizzando DynamoDBContext.

  • Ottieni un libro tramite l'Id.

    La tabella ProductCatalog dispone di Id come chiave primaria. Essa non dispone di una chiave di ordinamento come parte della chiave primaria. Per questa ragione, non ti sarà possibile eseguire query alla tabella. Puoi ottenere un item usandone il valore Id.

  • Eseguire le seguenti query sulla tabella Reply. La chiave primaria della tabella Reply è composta dagli attributi Id e ReplyDateTime. ReplyDateTime è una chiave di ordinamento, pertanto è possibile eseguire una query su questa tabella.

    • Cerca le risposte del thread di un forum pubblicate negli ultimi 15 giorni.

    • Cerca le risposte del thread di un forum pubblicate in un determinato intervallo di tempo.

  • Esegui la scansione della tabella ProductCatalog per trovare libri il cui prezzo sia inferiore rispetto a un valore specificato.

    Per motivi di prestazioni, è preferibile utilizzare l'operazione di query anziché l'operazione di scansione. Tuttavia, a volte potrebbe essere necessario eseguire la scansione di una tabella. Si supponga che si sia verificato un errore di immissione dei dati e che uno dei prezzi del libro sia stato impostato su un valore inferiore a 0. In questo esempio viene eseguita la scansione della tabella ProductCategory per trovare gli elementi del libro (ProductCategory è book) il cui prezzo è inferiore a 0.

Per istruzioni su come creare e un esempio di utilizzo, consulta Esempi di codice .NET.

Nota

Il seguente esempio non funziona con .NET Core poiché non supporta metodi sincroni. Per ulteriori informazioni, consulta API asincrone di AWS per .NET.

Esempio
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; } } }