使用 Amazon SDK for .NET 文档模型处理 DynamoDB 中的项目 - Amazon DynamoDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 Amazon SDK for .NET 文档模型处理 DynamoDB 中的项目

以下代码示例演示了如何使用 Amazon SDK for .NET 文档模型执行各种操作。您可以使用这些示例执行 CRUD、批处理、查询和事务操作。

要使用文档模型执行数据操作,您必须首先调用 Table.LoadTable 方法,它会创建 Table 类的实例来代表特定的表。以下 C# 示例创建的 Table 对象表示 Amazon DynamoDB 中的 ProductCatalog 表。

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 对象相同。如果您的原始项目有额外属性,新项目中将不再有这些属性。

下面是使用Amazon 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实例创建了一个具有Number、、StringString SetBoolean、和Null属性的项目。 (Null用于表示此商品QuantityOnHand的未知。) 对于 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) 和 (图片):

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 只会更新指定的输入属性。该项目的任何其他现有属性都不会更改。

下面是使用 Amazon 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);

批量写入 – 放置和删除多个项目

批量写入 是指批量放置和删除多个项目。该操作可让您仅调用一次 就向一个或多个表中放置或从一个或多个表中删除多个项目。下面是使用 Amazon SDK for .NET 文档模型 API 向表中放置或从表中删除多个项目的步骤。

  1. 执行 Table.LoadTable 方法,提供您要在其中执行批量操作的表的名称,从而创建 Table 对象。

  2. 对您在之前步骤中创建的表实例执行 createBatchWrite 方法,并创建 DocumentBatchWrite 对象。

  3. 使用 DocumentBatchWrite 对象方法指定您要上传或删除的文档。

  4. 调用 DocumentBatchWrite.Execute 方法执行批处理操作。

    使用文档模型 API 时,您可以批量指定任意数量的操作。但是,DynamoDB 限制了批量操作的数量以及批量操作中批的总大小。有关具体限制的更多信息,请参阅 BatchWriteItem。如果文档模型 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();

要了解可工作的示例,请参阅 示例:使用 Amazon SDK for .NET 文档模型 API 的批量操作

您可以使用 batchWrite 操作在多个表中执行放置和删除操作。下面是使用Amazon 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();