利用 AWS SDK for .NET 文件模型使用 DynamoDB 中的項目 - Amazon DynamoDB

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

利用 AWS SDK for .NET 文件模型使用 DynamoDB 中的項目

下列程式碼範例示範如何使用 AWS SDK for .NET 文件模型來執行各種操作。您可以使用這些範例來執行 CRUD、批次和交易操作。

若要使用文件模型執行資料操作,您必須先呼叫 Table.LoadTable 方法,該方法會建立代表特定資料表之 Table 類別的執行個體。以下 C# 程式碼範例會建立代表 Amazon DynamoDB 中 ProductCatalog 資料表的 Table 物件。

範例
Table table = Table.LoadTable(client, "ProductCatalog");
注意

一般來說,您會在應用程式的開頭使用 LoadTable 方法一次,因為它會呼叫 DescribeTable,並新增到 DynamoDB 的來回行程。

您接著便可使用 Table 物件執行不同資料操作。每一種資料操作都具有兩種類型的多載:一種只需接受最低需求的參數,另一種則接受選用的操作專屬組態資訊。例如,若要擷取項目,您必須提供資料表的主索引鍵值。在此案例中,您可以使用以下 GetItem 多載。

範例
// Get the item from a table that has a primary key that is composed of only a partition key. Table.GetItem(Primitive partitionKey); // Get the item from a table whose primary key is composed of both a partition key and sort key. Table.GetItem(Primitive partitionKey, Primitive sortKey);

您也可以傳遞選用的參數到這些方法。例如,上述 GetItem 會傳回整個項目,包含其全部的屬性。您可以選擇性的指定要擷取的屬性清單。在此案例中,您會使用以下 GetItem 多載,接受該操作專屬的組態物件參數。

範例
// Configuration object that specifies optional parameters. GetItemOperationConfig config = new GetItemOperationConfig() { AttributesToGet = new List<string>() { "Id", "Title" }, }; // Pass in the configuration to the GetItem method. // 1. Table that has only a partition key as primary key. Table.GetItem(Primitive partitionKey, GetItemOperationConfig config); // 2. Table that has both a partition key and a sort key. Table.GetItem(Primitive partitionKey, Primitive sortKey, GetItemOperationConfig config);

您可以使用組態物件指定數個選用參數,例如請求特定屬性清單,或指定頁面大小 (每一頁面的項目數)。每一種資料操作方法都具有自己的組態類別。舉例說明,您可以使用 GetItemOperationConfig 類別來為 GetItem 操作提供選項。舉例說明,您可以使用 PutItemOperationConfig 類別來為 PutItem 操作提供選用參數。

下節會討論 Table 類別支援的每一種資料操作。

把一個項目-表。 PutItem 方法

PutItem 方法會將輸入的 Document 執行個體上傳到資料表。若輸入 Document 中指定之主索引鍵的項目已存在於資料表中,則 PutItem 操作會取代整個現有項目。新項目和您為 PutItem 方法提供的 Document 物件完全相同。若您的原始項目具有任何額外的屬性,新的項目中便不再有這些屬性。

以下是使用 AWS SDK for .NET 文件模型將新項目放入資料表的步驟。

  1. 執行 Table.LoadTable 方法,該方法會提供您希望放入項目之資料表的名稱。

  2. 建立 Document 物件。該物件具有屬性名稱清單和其數值。

  3. 藉由將 Document 執行個體提供為參數,執行 Table.PutItem

下列 C# 程式碼範例示範上述工作。範例會將項目上傳至 ProductCatalog 資料表。

範例
Table table = Table.LoadTable(client, "ProductCatalog"); var book = new Document(); book["Id"] = 101; book["Title"] = "Book 101 Title"; book["ISBN"] = "11-11-11-11"; book["Authors"] = new List<string> { "Author 1", "Author 2" }; book["InStock"] = new DynamoDBBool(true); book["QuantityOnHand"] = new DynamoDBNull(); table.PutItem(book);

在上述範例中,Document實例會建立具有NumberStringString SetBoolean、和Null屬性的項目。 (用Null於表示此產品的QuantityOn手牌未知。) 針對 BooleanNull,請使用 DynamoDBBoolDynamoDBNull 建構函數方法。

在 DynamoDB 中,ListMap 資料類型可包含由其他資料類型組成的元素。下述為將這些資料類型映射到文件模型 API 的方式:

  • List:使用 DynamoDBList 建構函數。

  • Map:使用 Document 建構函數。

您可以修改上述範例,為項目新增 List 屬性。若要執行此作業,請使用 DynamoDBList 建構函數,如以下程式碼範例所示。

範例
Table table = Table.LoadTable(client, "ProductCatalog"); var book = new Document(); book["Id"] = 101; /*other attributes omitted for brevity...*/ var relatedItems = new DynamoDBList(); relatedItems.Add(341); relatedItems.Add(472); relatedItems.Add(649); book.Add("RelatedItems", relatedItems); table.PutItem(book);

若要為書籍新增 Map 屬性,您可以定義另一個 Document。以下程式碼範例示範如何執行此作業。

範例
Table table = Table.LoadTable(client, "ProductCatalog"); var book = new Document(); book["Id"] = 101; /*other attributes omitted for brevity...*/ var pictures = new Document(); pictures.Add("FrontView", "http://example.com/products/101_front.jpg" ); pictures.Add("RearView", "http://example.com/products/101_rear.jpg" ); book.Add("Pictures", pictures); table.PutItem(book);

這些範例是以「使用表達式時指定項目屬性」中顯示的項目為基礎的。文件模型可讓您建立複雜的巢狀屬性,例如在案例研究中顯示的 ProductReviews 屬性。

指定選用參數

您可以透過新增 PutItem 參數,設定 PutItemOperationConfig 操作的選用參數。如需可選參數的完整清單,請參閱PutItem。下列 C# 程式碼範例會將項目放於 ProductCatalog 資料表。它指定以下選用參數:

  • 要執行此條件式放入請求的 ConditionalExpression 參數。範例會建立表達式,指定 ISBN 屬性必須具有您要取代之項目中存在的特定值。

範例
Table table = Table.LoadTable(client, "ProductCatalog"); var book = new Document(); book["Id"] = 555; book["Title"] = "Book 555 Title"; book["Price"] = "25.00"; book["ISBN"] = "55-55-55-55"; book["Name"] = "Item 1 updated"; book["Authors"] = new List<string> { "Author x", "Author y" }; book["InStock"] = new DynamoDBBool(true); book["QuantityOnHand"] = new DynamoDBNull(); // Create a condition expression for the optional conditional put operation. Expression expr = new Expression(); expr.ExpressionStatement = "ISBN = :val"; expr.ExpressionAttributeValues[":val"] = "55-55-55-55"; PutItemOperationConfig config = new PutItemOperationConfig() { // Optional parameter. ConditionalExpression = expr }; table.PutItem(book, config);

獲取項目-表。 GetItem

GetItem 操作會將項目擷取為 Document 執行個體。您必須提供要擷取之項目的主索引鍵,如以下 C# 程式碼範例中所示。

範例
Table table = Table.LoadTable(client, "ProductCatalog"); Document document = table.GetItem(101); // Primary key 101.

GetItem 操作會傳回項目所有的屬性,並根據預設執行最終一致讀取 (請參閱「讀取一致性」)。

指定選用參數

您可以透過新增 GetItem 參數,為 GetItemOperationConfig 操作設定額外的選項。如需可選參數的完整清單,請參閱GetItem。下列 C# 程式碼範例會從 ProductCatalog 資料表擷取項目。它指定 GetItemOperationConfig,提供下列選用參數:

  • AttributesToGet 參數用於只擷取特定的屬性。

  • ConsistentRead 參數用於請求所有指定之屬性的最新值。如要進一步了解資料一致性,請參閱「讀取一致性」。

範例
Table table = Table.LoadTable(client, "ProductCatalog"); GetItemOperationConfig config = new GetItemOperationConfig() { AttributesToGet = new List<string>() { "Id", "Title", "Authors", "InStock", "QuantityOnHand" }, ConsistentRead = true }; Document doc = table.GetItem(101, config);

當您使用文件模型 API 擷取項目時,您可以存取傳回之 Document 物件中的個別元素,如下列範例所示。

範例
int id = doc["Id"].AsInt(); string title = doc["Title"].AsString(); List<string> authors = doc["Authors"].AsListOfString(); bool inStock = doc["InStock"].AsBoolean(); DynamoDBNull quantityOnHand = doc["QuantityOnHand"].AsDynamoDBNull();

針對類型為 ListMap 的屬性,以下為將這些屬性映射到文件模型 API 的方式:

  • List:使用 AsDynamoDBList 方法。

  • Map:使用 AsDocument 方法。

下列程式碼範例會示範如何從Document物件擷取 List Map (RelatedItems) 和 a (Pictures):

範例
DynamoDBList relatedItems = doc["RelatedItems"].AsDynamoDBList(); Document pictures = doc["Pictures"].AsDocument();

刪除物件-表格。 DeleteItem

DeleteItem 操作會從資料表刪除項目。您可以將項目的主索引鍵作為參數傳遞。或者,若您已讀取該項目,並具有相對應的 Document 物件,您可以將其做為參數傳遞給 DeleteItem 方法,如以下 C# 程式碼範例所示。

範例
Table table = Table.LoadTable(client, "ProductCatalog"); // Retrieve a book (a Document instance) Document document = table.GetItem(111); // 1) Delete using the Document instance. table.DeleteItem(document); // 2) Delete using the primary key. int partitionKey = 222; table.DeleteItem(partitionKey)

指定選用參數

您可以透過新增 Delete 參數,為 DeleteItemOperationConfig 操作設定額外的選項。如需可選參數的完整清單,請參閱DeleteTable。以下 C# 程式碼範例在指定以下兩個選用參數:

  • ConditionalExpression 參數用於確認要刪除之書籍項目的 ISBN 屬性具有指定的值。

  • ReturnValues 參數用於請求 Delete 方法傳回已刪除的項目。

範例
Table table = Table.LoadTable(client, "ProductCatalog"); int partitionKey = 111; Expression expr = new Expression(); expr.ExpressionStatement = "ISBN = :val"; expr.ExpressionAttributeValues[":val"] = "11-11-11-11"; // Specify optional parameters for Delete operation. DeleteItemOperationConfig config = new DeleteItemOperationConfig { ConditionalExpression = expr, ReturnValues = ReturnValues.AllOldAttributes // This is the only supported value when using the document model. }; // Delete the book. Document d = table.DeleteItem(partitionKey, config);

更新項目-表。 UpdateItem

UpdateItem 操作會更新現有的項目 (若存在的話)。若找不到具有指定之主索引鍵的項目,UpdateItem 操作會新增新的項目。

您可以使用 UpdateItem 操作更新現有的屬性值、為現有的集合新增新的屬性,或從現有的集合刪除屬性。您可以藉由建立描述欲執行之更新的 Document 執行個體,提供這些更新。

UpdateItem 動作會使用以下準則:

  • 若還沒有該項目,UpdateItem 會使用輸入中指定的主索引鍵新增項目。

  • 若已有該項目,UpdateItem 會套用更新,如下所示:

    • 將現有的屬性值取代為更新的值。

    • 若您在輸入中提供的屬性不存在,它會為項目新增新的屬性。

    • 若輸入的屬性值為 Null,它會刪除該屬性 (若有的話)。

注意

此中層UpdateItem作業不支援基礎 DynamoDB 作業支援的Add動作 (請參閱 UpdateItem)。

注意

PutItem 操作 (把一個項目-表。 PutItem 方法) 也可以執行更新。若您呼叫 PutItem 上傳項目,且該項目的主索引鍵已存在,PutItem 操作會取代整個項目。若現有項目中具有並未在放入 Document 上指定的屬性,PutItem 操作會刪除那些屬性。但是,UpdateItem 只會更新指定的輸入屬性。任何其他該項目現有的屬性都不會變更。

以下是使用 AWS SDK for .NET 文件模型更新項目的步驟:

  1. 藉由提供您希望執行更新操作之資料表的名稱,執行 Table.LoadTable 方法。

  2. 藉由提供所有您要執行的更新,建立 Document 執行個體。

    若要刪除現有的屬性,請將屬性值指定為 Null。

  3. 呼叫 Table.UpdateItem 方法並提供 Document 執行個體做為輸入參數。

    您必須在 Document 執行個體中或明確將其做為其中一個參數,提供主索引鍵。

下列 C# 程式碼範例示範上述工作。程式碼範例會更新 Book 資料表中的項目。UpdateItem 操作會更新現有的 Authors 屬性,刪除 PageCount 屬性,並新增新的 XYZ 屬性。Document 執行個體包含要更新之書籍的主索引鍵。

範例
Table table = Table.LoadTable(client, "ProductCatalog"); var book = new Document(); // Set the attributes that you wish to update. book["Id"] = 111; // Primary key. // Replace the authors attribute. book["Authors"] = new List<string> { "Author x", "Author y" }; // Add a new attribute. book["XYZ"] = 12345; // Delete the existing PageCount attribute. book["PageCount"] = null; table.Update(book);

指定選用參數

您可以透過新增 UpdateItem 參數,為 UpdateItemOperationConfig 操作設定額外的選項。如需可選參數的完整清單,請參閱UpdateItem

以下 C# 程式碼範例會將書籍項目的價格更新為 25。它會指定以下兩個選用參數:

  • ConditionalExpression 參數會識別數值為 20,並且您預期會存在的 Price 屬性。

  • ReturnValues 參數會請求 UpdateItem 操作傳回已更新的項目。

範例
Table table = Table.LoadTable(client, "ProductCatalog"); string partitionKey = "111"; var book = new Document(); book["Id"] = partitionKey; book["Price"] = 25; Expression expr = new Expression(); expr.ExpressionStatement = "Price = :val"; expr.ExpressionAttributeValues[":val"] = "20"; UpdateItemOperationConfig config = new UpdateItemOperationConfig() { ConditionalExpression = expr, ReturnValues = ReturnValues.AllOldAttributes }; Document d1 = table.Update(book, config);

批次寫入 - 放入和刪除多個項目

批次寫入表示在一個批次中放入和刪除多個項目。您可利用此操作,在單一呼叫中對來自一或多個資料表的多個項目,進行放入與刪除。以下是使用 AWS SDK for .NET 文檔模型 API 從表中放置或刪除多個項目的步驟。

  1. 透過提供您希望執行批次操作之資料表的名稱,執行 Table.LoadTable 方法,建立 Table 物件。

  2. 在您於上述步驟中建立的資料表執行個體上執行 createBatchWrite 方法,建立 DocumentBatchWrite 物件。

  3. 使用 DocumentBatchWrite 物件方法指定您要上傳或刪除的文件。

  4. 呼叫 DocumentBatchWrite.Execute 方法執行批次操作。

    當使用文件模型 API 時,您可以在單一批次中指定任何數目的操作。但 DynamoDB 會限制批次中的操作數目,以及批次操作中的批次總大小。如需有關特定限制的詳細資訊,請參閱BatchWrite項目。若文件模型 API 偵測到您的批次寫入請求超過允許的寫入請求次數,或是批次的 HTTP 裝載大小超過 BatchWriteItem 所允許的限制,它會將批次分成數個較小的批次。此外,如果批次寫入的回應傳回未處理的項目,文件模型 API 會自動傳送含有這些未處理項目的另一個批次請求。

下列 C# 程式碼範例示範前述步驟。程式碼範例會使用批次寫入操作執行兩次寫入:上傳一個書籍項目,及刪除另一個書籍項目。

Table productCatalog = Table.LoadTable(client, "ProductCatalog"); var batchWrite = productCatalog.CreateBatchWrite(); var book1 = new Document(); book1["Id"] = 902; book1["Title"] = "My book1 in batch write using .NET document model"; book1["Price"] = 10; book1["Authors"] = new List<string> { "Author 1", "Author 2", "Author 3" }; book1["InStock"] = new DynamoDBBool(true); book1["QuantityOnHand"] = 5; batchWrite.AddDocumentToPut(book1); // specify delete item using overload that takes PK. batchWrite.AddKeyToDelete(12345); batchWrite.Execute();

如需運作範例,請參閱 範例:使用 AWS SDK for .NET 文件模型 API 的 Batch 作業

您可以使用 batchWrite 操作在多個資料表上執行放入和刪除操作。以下是使用 AWS SDK for .NET 文檔模型放置或刪除多個表中的多個項目的步驟。

  1. 您會為每個希望放入或刪除多個項目的資料表建立 DocumentBatchWrite 執行個體,如上述程序中所說明。

  2. 建立 MultiTableDocumentBatchWrite 執行個體,然後將個別 DocumentBatchWrite 物件新增到該執行個體。

  3. 執行 MultiTableDocumentBatchWrite.Execute 方法。

下列 C# 程式碼範例示範前述步驟。程式碼範例會使用批次寫入操作,執行以下寫入操作:

  • Forum 資料表項目中放入一個新的項目。

  • Thread 資料表放入一個項目,並從相同資料表中刪除一個項目。

// 1. Specify item to add in the Forum table. Table forum = Table.LoadTable(client, "Forum"); var forumBatchWrite = forum.CreateBatchWrite(); var forum1 = new Document(); forum1["Name"] = "Test BatchWrite Forum"; forum1["Threads"] = 0; forumBatchWrite.AddDocumentToPut(forum1); // 2a. Specify item to add in the Thread table. Table thread = Table.LoadTable(client, "Thread"); var threadBatchWrite = thread.CreateBatchWrite(); var thread1 = new Document(); thread1["ForumName"] = "Amazon S3 forum"; thread1["Subject"] = "My sample question"; thread1["Message"] = "Message text"; thread1["KeywordTags"] = new List<string>{ "Amazon S3", "Bucket" }; threadBatchWrite.AddDocumentToPut(thread1); // 2b. Specify item to delete from the Thread table. threadBatchWrite.AddKeyToDelete("someForumName", "someSubject"); // 3. Create multi-table batch. var superBatch = new MultiTableDocumentBatchWrite(); superBatch.AddBatch(forumBatchWrite); superBatch.AddBatch(threadBatchWrite); superBatch.Execute();