使用 Amazon DynamoDB NoSQL 資料庫 - AWS SDK for .NET (V4)

第 4 版 (V4) AWS SDK for .NET 已發行!

如需有關中斷變更和遷移應用程式的資訊,請參閱遷移主題

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

使用 Amazon DynamoDB NoSQL 資料庫

注意

這些主題中的程式設計模型同時存在於 .NET Framework 和 .NET (Core) 中,但呼叫慣例會有所不同,無論是同步或非同步。

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

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

低階模型

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

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

下列範例示範如何使用低階模型來建立資料表、修改資料表,以及將項目插入 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 中的資料。此模型特別適用於存取資料表和資料表中的項目。您透過 Amazon.DynamoDBv2.DocumentModel 命名空間存取此模型。

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

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

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

建立資料表的表示法

若要使用文件模型執行資料操作,您必須先建立代表特定資料表的 Table類別執行個體。有兩種主要方式可以執行此操作。

LoadTable 方法

第一個機制是使用 Table類別的其中一個靜態LoadTable方法,類似下列範例:

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

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

TableBuilder

替代機制 TableBuilder類別在 AWSSDK.DynamoDBv2 NuGet 套件的 3.7.203 版中推出。此機制可以透過移除特定隱含方法呼叫來解決上述行為;特別是 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 方法的字串。您可以使用 DynamoDBEntry類別的各種「As【type】」方法進行明確轉換。例如,您可以透過 AsGuid()方法,將 的值IdPrimitive資料類型明確轉換為 GUID:

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

物件持續性模型

物件持久性程式設計模型專為在 DynamoDB 中存放、載入和查詢 .NET 物件而設計。您透過 Amazon.DynamoDBv2.DataModel 命名空間存取此模型。

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

如需 DynamoDB 物件持久性程式設計模型的詳細資訊,請參閱《Amazon DynamoDB 開發人員指南》中的 .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 設定為 true,如第二個範例所示,物件持久性模型的方法,例如 SaveAsync和 完全QueryAsync依賴 Reply類別中定義的屬性。在此情況下,不會呼叫 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 Framework,則可以在 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類別也在 AWSSDK.DynamoDBv2 NuGet 套件的 3.7.203 版中推出。

    // 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 程式、資訊和範例

低階模型、資訊和範例

文件模型、資訊和範例

物件持久性模型、資訊和範例

其他實用資訊