.NET:文档模型
主题
Amazon SDK for .NET 提供了文档模型类,其中封装了一些低级 Amazon DynamoDB 操作来进一步简化编码工作。在文档模型中,主要的类有 Table
和 Document
。Table
类可以提供 PutItem
、GetItem
和 DeleteItem
等数据操作方法。同时,它还提供 Query
和 Scan
方法。Document
类表示表中的一个项目。
您可以在 Amazon.DynamoDBv2.DocumentModel
命名空间中找到前面所述的文档模型类。
文档模型不支持的操作
您不能使用这些文档模型类创建、更新和删除表。不过,文档模型支持大部分常见的数据操作。
获取项目 – Table.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();
对于 List
或 Map
类型的属性,下面介绍这些属性如何映射到文档模型 API:
-
List
— 使用AsDynamoDBList
方法。 -
Map
— 使用AsDocument
方法。
以下代码示例说明如何从 Document
对象检索 List
(RelatedItems) 和 Map
(Pictures):
例
DynamoDBList relatedItems = doc["RelatedItems"].AsDynamoDBList(); Document pictures = doc["Pictures"].AsDocument();
删除项目 – Table.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);
更新项目 – Table.UpdateItem
UpdateItem
操作可以更新现有的项目(如果存在)。如果未找到具有指定主键的项目,UpdateItem
操作会添加新项目。
您可以使用 UpdateItem
操作更新现有属性值、向现有集合中添加新属性,或者从现有集合中删除属性。您可以通过创建用于说明要执行的更新的 Document
实例来提供这些更新。
UpdateItem
操作遵循以下指导原则:
-
如果项目不存在,
UpdateItem
会添加一个新项目 (使用输入中指定的主键)。 -
如果项目存在,则
UpdateItem
按照以下方式应用更新:-
使用更新中的值替换现有属性值。
-
如果您在输入中提供的属性不存在,系统就会为项目添加新属性。
-
如果输入属性值为 Null,系统会删除属性(如果存在)。
-
此中级 UpdateItem
操作不支持底层 DynamoDB 操作支持的 Add
操作(请参阅 UpdateItem)。
PutItem
操作(放置项目 – Table.PutItem 方法)还可以执行更新。如果您调用 PutItem
上传项目,并且主键存在,则 PutItem
操作会替换整个项目。如果现有项目中有属性,并且这些属性未在所放置的 Document
中指定,那么 PutItem
操作就会删除这些属性。但是,UpdateItem
只会更新指定的输入属性。该项目的任何其他现有属性都不会更改。
下面是使用 Amazon SDK for .NET 文档模型更新项目的步骤:
-
提供表名称(指定要对哪个表执行更新操作),以执行
Table.LoadTable
方法。 -
提供您要执行的所有更新,创建
Document
实例。要删除现有属性,请将属性值指定为 Null。
-
调用
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 向表中放置或从表中删除多个项目的步骤。
-
执行
Table.LoadTable
方法,提供您要在其中执行批量操作的表的名称,从而创建Table
对象。 -
对您在之前步骤中创建的表实例执行
CreateBatchWrite
方法,并创建DocumentBatchWrite
对象。 -
使用
DocumentBatchWrite
对象方法指定您要上传或删除的文档。 -
调用
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文档模型向多个表中放置或从多个表中删除多个项目的步骤。
-
为要放置或删除多个项目的每个表创建
DocumentBatchWrite
实例(如上述流程所述)。 -
创建一个
MultiTableDocumentBatchWrite
的实例并在其中添加各个DocumentBatchWrite
对象。 -
运行
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();