使用 Amazon DynamoDB 資 NoSQL 庫 - AWS SDK for .NET

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 Amazon DynamoDB 資 NoSQL 庫

注意

這些主題中的程式設計模型都存在於 .NET Framework 和 .NET (核心) 中,但呼叫慣例不同,無論是同步還是非同步。

AWS SDK for .NET 支援 Amazon DynamoDB,這是一種快速的 NoSQL 資料庫服務由. AWS SDK 提供三種用於與 DynamoDB 通訊的程式設計模型:低階模型、文件模型和持續性模型。

以下資訊介紹了這些模型及其 API、提供如何及何時使用它們的範例,並提供中其他 DynamoDB 程式設計資源的連結。 AWS SDK for .NET

低階模型

低階程式設計模型會將直接呼叫包裝至 DynamoDB 服務。您透過 Amazon.DynamoDBv2 命名空間存取此模型。

三個模型中,低階模型要求您撰寫最多的程式碼。例如,您必須在 DynamoDB 中將 .NET 資料類型轉換為它們的對等項目。不過,這個模型可讓您存取最多的功能。

下列範例說明如何使用低階模型建立表格、修改表格,以及將項目插入 DynamoDB 中的表格。

建立資料表

在下列範例中,您可以使用 AmazonDynamoDBClient 類別的 CreateTable 方法建立資料表。此 CreateTable 方法使用CreateTableRequest 類別的執行個體,其中包含特性,例如必要項目屬性名稱、主索引鍵定義和傳輸量。CreateTable 方法傳回 CreateTableResponse 類別的執行個體。

// using Amazon.DynamoDBv2; // using Amazon.DynamoDBv2.Model; var client = new AmazonDynamoDBClient(); Console.WriteLine("Getting list of tables"); List<string> currentTables = client.ListTables().TableNames; Console.WriteLine("Number of tables: " + currentTables.Count); if (!currentTables.Contains("AnimalsInventory")) { var request = new CreateTableRequest { TableName = "AnimalsInventory", AttributeDefinitions = new List<AttributeDefinition> { new AttributeDefinition { AttributeName = "Id", // "S" = string, "N" = number, and so on. AttributeType = "N" }, new AttributeDefinition { AttributeName = "Type", AttributeType = "S" } }, KeySchema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Id", // "HASH" = hash key, "RANGE" = range key. KeyType = "HASH" }, new KeySchemaElement { AttributeName = "Type", KeyType = "RANGE" }, }, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = 10, WriteCapacityUnits = 5 }, }; var response = client.CreateTable(request); Console.WriteLine("Table created with request ID: " + response.ResponseMetadata.RequestId); }

確認資料表已準備修改

在您可以變更或修改資料表之前,資料表必須做好修改的準備。下列範例顯示如何使用低階模型來驗證 DynamoDB 中的資料表是否已就緒。在這個範例中,透過 AmazonDynamoDBClient 類別的 DescribeTable方法來做為檢查目標資料表的參考。程式碼每 5 秒檢查一次資料表的 TableStatus 屬性值。當狀態是設定為 ACTIVE,資料表已準備好做修改。

// using Amazon.DynamoDBv2; // using Amazon.DynamoDBv2.Model; var client = new AmazonDynamoDBClient(); var status = ""; do { // Wait 5 seconds before checking (again). System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5)); try { var response = client.DescribeTable(new DescribeTableRequest { TableName = "AnimalsInventory" }); Console.WriteLine("Table = {0}, Status = {1}", response.Table.TableName, response.Table.TableStatus); status = response.Table.TableStatus; } catch (ResourceNotFoundException) { // DescribeTable is eventually consistent. So you might // get resource not found. } } while (status != TableStatus.ACTIVE);

將項目插入到資料表

在下列範例中,您可以使用低階模型將兩個項目插入 DynamoDB 的表格中。每個項目使用 PutItemRequest 類別的執行個體,透過 AmazonDynamoDBClient 類別的 PutItem 方法插入。PutItemRequest 類別的兩個執行個體的每一個,採用具有一系列的項目屬性值,且其項目將插入的資料表名稱。

// using Amazon.DynamoDBv2; // using Amazon.DynamoDBv2.Model; var client = new AmazonDynamoDBClient(); var request1 = new PutItemRequest { TableName = "AnimalsInventory", Item = new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = "1" }}, { "Type", new AttributeValue { S = "Dog" }}, { "Name", new AttributeValue { S = "Fido" }} } }; var request2 = new PutItemRequest { TableName = "AnimalsInventory", Item = new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = "2" }}, { "Type", new AttributeValue { S = "Cat" }}, { "Name", new AttributeValue { S = "Patches" }} } }; client.PutItem(request1); client.PutItem(request2);

文件模型

文件程式設計模型提供了一種更簡單的方式來處理 DynamoDB 中的資料。此模型特別適用於存取資料表和資料表中的項目。您可以通過亞馬遜訪問此模型。 DocumentModel命名空間。

與低階程式設計模型相比,文件模型更容易根據 DynamoDB 資料進行程式碼。例如,您不必在 DynamoDB 中將盡可能多的 .NET 資料類型轉換為它們的對等項目。不過,這個模型不提供如同低階程式設計模型數量一樣多功能的存取權。例如,您可以使用此模型來建立、擷取、更新和刪除資料表中的項目。不過,若要建立資料表,您必須使用低階模型。相較於物件持續性模型,這個模型要求您編寫更多的程式碼來存放、載入和查詢 .NET 物件。

如需有關 DynamoDB 文件程式設計模型的詳細資訊,請參閱 Amazon Dynam oDB 開發人員指南中的 .NET:文件模型

以下各節提供有關如何建立所需 DynamoDB 表示的資訊,以及如何使用文件模型將項目插入表格並從表格中取得項目的範例。

建立表格的表示

若要使用文件模型執行資料作業,您必須先建立代表特定資料表之Table類別的執行個體。有兩種主要方法可以做到這一點。

LoadTable 方法

第一種機制是使用類的靜態LoadTable方法之一,Table類似於下面的例子:

var client = new AmazonDynamoDBClient(); Table table = Table.LoadTable(client, "Reply");
注意

雖然這種機制可以運作,但在某些情況下,由於冷啟動和執行緒集區行為,有時會導致額外的延遲或死結。如需有關這些行為的詳細資訊,請參閱部落格文章改進的 DynamoDB 初始化模式。 AWS SDK for .NET

TableBuilder

另一種機制 (TableBuilder類別) 是在 .DynamoDBv2 套件的 3.7.203 版中引入的 AWSSDK。 NuGet 這種機制可以通過刪除某些隱式方法調用來解決上述行為; 特別是該DescribeTable方法。此機制的使用方式類似於下列範例:

var client = new AmazonDynamoDBClient(); var table = new TableBuilder(client, "Reply") .AddHashKey("Id", DynamoDBEntryType.String) .AddRangeKey("ReplyDateTime", DynamoDBEntryType.String) .AddGlobalSecondaryIndex("PostedBy-Message-index", "Author", DynamoDBEntryType.String, "Message", DynamoDBEntryType.String) .Build();

如需有關此替代機制的詳細資訊,請再次參閱部落格文章改進的 DynamoDB 初始化模式。 AWS SDK for .NET

將項目插入表格

在下列範例中,會透過Table類別的PutItemAsync方法,將回覆插入回覆資料表。此 PutItemAsync 方法採用 Document 類別的執行個體; Document 類別只是一組初始化屬性。

using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DocumentModel; // Create a representation of the "Reply" table // by using one of the mechanisms described previously. // Then, add a reply to the table. var newReply = new Document(); newReply["Id"] = Guid.NewGuid().ToString(); newReply["ReplyDateTime"] = DateTime.UtcNow; newReply["PostedBy"] = "Author1"; newReply["Message"] = "Thank you!"; await table.PutItemAsync(newReply);

從表格中取得項目

在下面的例子中,一個回复是通過Table類的GetItemAsync方法檢索。若要決定要取得的回覆,此方GetItemAsync法會使用目標回覆的 hash-and-range 主索引鍵。

using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DocumentModel; // Create a representation of the "Reply" table // by using one of the mechanisms described previously. // Then, get a reply from the table // where "guid" is the hash key and "datetime" is the range key. var reply = await table.GetItemAsync(guid, datetime); Console.WriteLine("Id = " + reply["Id"]); Console.WriteLine("ReplyDateTime = " + reply["ReplyDateTime"]); Console.WriteLine("PostedBy = " + reply["PostedBy"]); Console.WriteLine("Message = " + reply["Message"]);

上述範例會隱含地將資料表值轉換為WriteLine方法的字串。您可以通過使用類的各種「As [type]」方法進行明確DynamoDBEntry的轉換。例如,您可以透過下列AsGuid()方法明確地將的值IdPrimitive資料類型轉換為 GUID:

var guid = reply["Id"].AsGuid();

物件持續性模型

物件持續性程式設計模型是專為在 DynamoDB 中儲存、載入和查詢 .NET 物件而設計的。您可以通過亞馬遜訪問此模型。 DataModel命名空間。

在這三個模型中,每當您儲存、載入或查詢 DynamoDB 資料時,物件持續性模型最容易編寫程式碼。例如,您可以直接使用 DynamoDB 資料類型。不過,此模型僅提供存取 DynamoDB 中儲存、載入和查詢 .NET 物件的作業。例如,您可以使用此模型來建立、擷取、更新和刪除資料表中的項目。不過,您必須先使用低階模型建立資料表,然後使用此模型將 .NET 類別對應至資料表。

如需 DynamoDB 物件持續性程式設計模型的詳細資訊,請參閱 Amazon Dynam oDB 開發人員指南中的 .NET:物件持續性模型

下列範例說明如何定義代表 DynamoDB 項目的 .NET 類別、使用 .NET 類別的執行個體將項目插入 DynamoDB 資料表,以及如何使用 .NET 類別的執行個體從表格取得項目。

定義一個 .NET 類,代表表一個表中的項

在類別定義的下列範例中,DynamoDBTable屬性會指定資料表名稱,而DynamoDBHashKeyDynamoDBRangeKey屬性會建模資料表的 hash-and-range 主索引鍵。該DynamoDBGlobalSecondaryIndexHashKey屬性被定義,以便可以構建特定作者對回复的查詢。

using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; [DynamoDBTable("Reply")] public class Reply { [DynamoDBHashKey] public string Id { get; set; } [DynamoDBRangeKey(StoreAsEpoch = false)] public DateTime ReplyDateTime { get; set; } [DynamoDBGlobalSecondaryIndexHashKey("PostedBy-Message-Index", AttributeName ="PostedBy")] public string Author { get; set; } [DynamoDBGlobalSecondaryIndexRangeKey("PostedBy-Message-Index")] public string Message { get; set; } }

建立物件持續性模型的前後關聯

若要使用 DynamoDB 的物件持續性程式設計模型,您必須建立上下文,以提供與 DynamoDB 的連線,並可讓您存取表格、執行各種作業以及執行查詢。

基本上下文

下列範例會示範如何建立最基本的前後關聯。

using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; var client = new AmazonDynamoDBClient(); var context = new DynamoDBContext(client);

與 DisableFetchingTableMetadata 屬性的上下文

下列範例會示範如何另外設定DynamoDBContextConfig類別的DisableFetchingTableMetadata屬性,以防止對DescribeTable方法進行隱含呼叫。

using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; var client = new AmazonDynamoDBClient(); var context = new DynamoDBContext(client, new DynamoDBContextConfig { DisableFetchingTableMetadata = true });

如果DisableFetchingTableMetadata屬性設定為 false (預設值),如第一個範例所示,您可以省略描述Reply類別中表格項目索引鍵和索引結構的屬性。而是透過隱含呼叫DescribeTable方法來推斷這些屬性。如果DisableFetchingTableMetadata設定為 (如第二個範例所示) 物件持續性模型的方法,例如SaveAsync和完全QueryAsync依賴於Reply類別中定義的屬性。true在這種情況下,不會發生對該DescribeTable方法的調用。

注意

在某些情況下,呼叫方DescribeTable法有時會因為冷啟動和執行緒集區行為而導致額外的延遲或死結。出於這個原因,有時避免調用該方法是有利的。

如需有關這些行為的詳細資訊,請參閱部落格文章改進的 DynamoDB 初始化模式。 AWS SDK for .NET

使用 .NET 類別的執行個體將項目插入資料表

在此範例中,項目會透過DynamoDBContext類別的SaveAsync方法插入,該方法會接受代表項目之 .NET 類別的初始化執行個體。

using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; // Create an appropriate context for the object persistence programming model, // examples of which have been described earlier. // Create an object that represents the new item. var reply = new Reply() { Id = Guid.NewGuid().ToString(), ReplyDateTime = DateTime.UtcNow, Author = "Author1", Message = "Thank you!" }; // Insert the item into the table. await context.SaveAsync<Reply>(reply, new DynamoDBOperationConfig { IndexName = "PostedBy-Message-index" });

使用 .NET 類的實例從表中獲取項目

在這個例子中,一個查詢被創建,通過使用DynamoDBContext類的QueryAsync方法來查找「Author1」的所有記錄。然後,項目通過查詢的GetNextSetAsync方法檢索。

using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.DataModel; // Create an appropriate context for the object persistence programming model, // examples of which have been described earlier. // Construct a query that finds all replies by a specific author. var query = context.QueryAsync<Reply>("Author1", new DynamoDBOperationConfig { IndexName = "PostedBy-Message-index" }); // Display the result. var set = await query.GetNextSetAsync(); foreach (var item in set) { Console.WriteLine("Id = " + item.Id); Console.WriteLine("ReplyDateTime = " + item.ReplyDateTime); Console.WriteLine("PostedBy = " + item.Author); Console.WriteLine("Message = " + item.Message); }

有關物件持續性模型的其他資訊

上面顯示的例子和解釋有時會包含所謂的DynamoDBContext類的屬性DisableFetchingTableMetadata。這個屬性是在 AWSSDK.DynamoDBv2 NuGet 套件 3.7.203 版中引入的,可讓您避免某些可能因冷啟動和執行緒集區行為而造成額外延遲或死結的情況。如需詳細資訊,請參閱部落格文章改進的 DynamoDB 初始化模式。 AWS SDK for .NET

以下是有關此屬性的一些其他信息。

  • 如果您使用 .NET 框架,則可以在您的app.configweb.config文件中全局設置此屬性。

  • 這個屬性可以全域使用AWSConfigsDynamoDB類別來設定,如下列範例所示。

    // Set the DisableFetchingTableMetadata property globally // before constructing any context objects. AWSConfigsDynamoDB.Context.DisableFetchingTableMetadata = true; var client = new AmazonDynamoDBClient(); var context = new DynamoDBContext(client);
  • 在某些情況下,您無法將 DynamoDB 屬性新增至 .NET 類別;例如,如果類別是在相依性中定義的。在這種情況下,仍然可以利用該DisableFetchingTableMetadata屬性。若要這麼做,除了DisableFetchingTableMetadata屬性之外,請使用該TableBuilder類別。此TableBuilder類別也是在 .7 版套件的 3.7.203 版中引入的 AWSSDK。 NuGet

    // Set the DisableFetchingTableMetadata property globally // before constructing any context objects. AWSConfigsDynamoDB.Context.DisableFetchingTableMetadata = true; var client = new AmazonDynamoDBClient(); var context = new DynamoDBContext(client); var table = new TableBuilder(client, "Reply") .AddHashKey("Id", DynamoDBEntryType.String) .AddRangeKey("ReplyDateTime", DynamoDBEntryType.String) .AddGlobalSecondaryIndex("PostedBy-Message-index", "Author", DynamoDBEntryType.String, "Message", DynamoDBEntryType.String) .Build(); // This registers the "Reply" table we constructed via the builder. context.RegisterTableDefinition(table); // Now operations like this will work, // even if the Reply class was not annotated with this index. var query = context.QueryAsync<Reply>("Author1", new DynamoDBOperationConfig() { IndexName = "PostedBy-Message-index" });

其他資訊

使用 AWS SDK for .NET 對 DynamoDB 資訊和範例進行程式設計 **

低階模型資訊和範例

文件模型資訊和範例

對象持久性模型信息和實例