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

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

使用项目:.NET

您可以使用 Amazon SDK for .NET 低级别 API 对表中的项目执行典型的创建、读取、更新和删除 (CRUD) 操作。以下是使用 .NET 低级 API 执行数据 CRUD 操作的常见步骤。

  1. 创建 AmazonDynamoDBClient 类(客户端)的实例。

  2. 在相应的请求对象中提供特定于操作的必需参数。

    例如,将 PutItemRequest 请求对象,并使用 GetItemRequest 检索现有项目时请求对象。

    您可以使用请求对象同时提供所需参数和可选参数。

  3. 传入之前步骤创建的请求对象,运行客户端提供的适当方法。

    这些区域有:AmazonDynamoDBClient 客户端提供 PutItemGetItemUpdateItemDeleteItem 方法进行 CRUD 操作。

放置项目

PutItem 方法将项目上传到表。如果项目已存在,则会替换整个项目。

注意

如果您不想替换整个项目,而只希望更新特定属性,那么您可以使用 UpdateItem 方法。有关更多信息,请参阅 更新项目

以下是使用低级别 .NET SDK API 上传项目的步骤。

  1. 创建 AmazonDynamoDBClient 类的实例。

  2. 提供所需的参数,方法是创建 PutItemRequest 类。

    要放置项目,您必须提供表名称和项目。

  3. 通过提供您在之前步骤中创建的 PutItemRequest 对象,运行 PutItem 方法。

以下 C# 示例演示了上述步骤。该示例将一个项目上传到 ProductCatalog 表。

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new PutItemRequest { TableName = tableName, Item = new Dictionary<string, AttributeValue>() { { "Id", new AttributeValue { N = "201" }}, { "Title", new AttributeValue { S = "Book 201 Title" }}, { "ISBN", new AttributeValue { S = "11-11-11-11" }}, { "Price", new AttributeValue { S = "20.00" }}, { "Authors", new AttributeValue { SS = new List<string>{"Author1", "Author2"} } } } }; client.PutItem(request);

在上一示例中,您上传的图书项目包含 IdTitleISBNAuthors 属性。请注意,Id 是数字类型属性,所有其他属性都是字符串类型。作者是 String 设置。

指定可选参数

您也可以使用 PutItemRequest 对象,如以下 C# 示例所示。该示例指定了以下可选参数:

  • ExpressionAttributeNamesExpressionAttributeValuesConditionExpression 指定只有当现有项目具有特定值 ISBN 属性时,才可替换该项目。

  • ReturnValues 参数,用于请求响应中的旧项目。

var request = new PutItemRequest { TableName = tableName, Item = new Dictionary<string, AttributeValue>() { { "Id", new AttributeValue { N = "104" }}, { "Title", new AttributeValue { S = "Book 104 Title" }}, { "ISBN", new AttributeValue { S = "444-4444444444" }}, { "Authors", new AttributeValue { SS = new List<string>{"Author3"}}} }, // Optional parameters. ExpressionAttributeNames = new Dictionary<string,string>() { {"#I", "ISBN"} }, ExpressionAttributeValues = new Dictionary<string, AttributeValue>() { {":isbn",new AttributeValue {S = "444-4444444444"}} }, ConditionExpression = "#I = :isbn" }; var response = client.PutItem(request);

有关更多信息,请参阅PutItem

获取项目

GetItem 方法检索项目。

注意

要检索多个项目,您可以使用 BatchGetItem 方法。有关更多信息,请参阅 批处理获取:获取多个项目

下面是使用低级 Amazon SDK for .NET API 检索现有项目的步骤。

  1. 创建 AmazonDynamoDBClient 类的实例。

  2. 创建 GetItemRequest 类实例,提供所需的参数。

    要获取项目,您必须提供项目的表名称和主键。

  3. 通过提供您在之前步骤中创建的 GetItemRequest 对象,运行 GetItem 方法。

以下 C# 示例演示了上述步骤。示例从 ProductCatalog 表检索项目。

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new GetItemRequest { TableName = tableName, Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } }, }; var response = client.GetItem(request); // Check the response. var result = response.GetItemResult; var attributeMap = result.Item; // Attribute list in the response.

指定可选参数

您也可以使用 GetItemRequest 对象提供可选参数,如以下 C# 示例所示。该示例指定了以下可选参数:

  • ProjectionExpression 参数,指定要检索的属性。

  • ConsistentRead 参数,执行强一致性读取。要了解有关读取一致性的更多信息,请参阅 读取一致性

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new GetItemRequest { TableName = tableName, Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } }, // Optional parameters. ProjectionExpression = "Id, ISBN, Title, Authors", ConsistentRead = true }; var response = client.GetItem(request); // Check the response. var result = response.GetItemResult; var attributeMap = result.Item;

有关更多信息,请参阅GetItem

更新项目

UpdateItem 方法更新现有的项目(如果存在)。您可以使用 UpdateItem 操作更新现有属性值,添加新属性,或者从现有集合中删除属性。如果未找到具有指定主键的项目,将添加新项目。

UpdateItem 操作遵循以下指导原则:

  • 如果项目不存在,UpdateItem 会添加一个新项目 (使用输入中指定的主键)。

  • 如果项目存在,则 UpdateItem 按照以下方式应用更新:

    • 使用更新中的值替换现有属性值。

    • 如果您在输入中提供的属性不存在,系统就会为项目添加新属性。

    • 如果输入属性为 Null,系统会删除属性(如果存在)。

    • 如果您对 Action 使用 ADD,您可以将值添加到现有集合(字符串或数字集),或以数学方式从现有数字属性值中添加(使用正数)或减去(使用负数)。

注意

PutItem 操作还可以执行更新。有关更多信息,请参阅 放置项目。例如,如果调用 PutItem 上传项目,并且主键存在,则 PutItem 操作会替换整个项目。如果现有项目中有属性,并且这些属性未在输入中指定,那么 PutItem 操作就会删除这些属性。但是,UpdateItem 仅更新指定的输入属性。该项目的任何其他现有属性都不会更改。

以下是使用低级 .NET SDK API 更新现有项目的步骤:

  1. 创建 AmazonDynamoDBClient 类的实例。

  2. 创建 UpdateItemRequest 类实例,提供所需的参数。

    这是描述所有更新(如添加属性、更新现有属性或删除属性)的请求对象。要删除现有属性,请将属性名称指定为 Null 值。

  3. 通过提供您在之前步骤中创建的 UpdateItemRequest 对象,运行 UpdateItem 方法。

以下 C# 代码示例演示了上述步骤。示例更新 ProductCatalog 表中的书本项目。将新作者添加到 Authors 集合,删除现有 ISBN 属性。另外还降低了价格 (-1)。

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new UpdateItemRequest { TableName = tableName, Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } }, ExpressionAttributeNames = new Dictionary<string,string>() { {"#A", "Authors"}, {"#P", "Price"}, {"#NA", "NewAttribute"}, {"#I", "ISBN"} }, ExpressionAttributeValues = new Dictionary<string, AttributeValue>() { {":auth",new AttributeValue { SS = {"Author YY","Author ZZ"}}}, {":p",new AttributeValue {N = "1"}}, {":newattr",new AttributeValue {S = "someValue"}}, }, // This expression does the following: // 1) Adds two new authors to the list // 2) Reduces the price // 3) Adds a new attribute to the item // 4) Removes the ISBN attribute from the item UpdateExpression = "ADD #A :auth SET #P = #P - :p, #NA = :newattr REMOVE #I" }; var response = client.UpdateItem(request);

指定可选参数

您也可以使用 UpdateItemRequest 对象提供可选参数,如以下 C# 示例所示。它指定以下两个可选参数:

  • ExpressionAttributeValuesConditionExpression,指定仅当现有价格为 20.00 时才能更新价格。

  • ReturnValues 参数,用于请求响应中的更新项目。

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new UpdateItemRequest { Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "202" } } }, // Update price only if the current price is 20.00. ExpressionAttributeNames = new Dictionary<string,string>() { {"#P", "Price"} }, ExpressionAttributeValues = new Dictionary<string, AttributeValue>() { {":newprice",new AttributeValue {N = "22"}}, {":currprice",new AttributeValue {N = "20"}} }, UpdateExpression = "SET #P = :newprice", ConditionExpression = "#P = :currprice", TableName = tableName, ReturnValues = "ALL_NEW" // Return all the attributes of the updated item. }; var response = client.UpdateItem(request);

有关更多信息,请参阅UpdateItem

原子计数器

您可以使用 updateItem 实现原子计数器,并使用该计数器来递增或递减现有属性的值而不会干扰其他写入请求。要更新原子计数器,请使用 updateItemUpdateExpression 参数为 Number 类型属性,ADDAction

以下示例演示了这一用法,将 Quantity 属性递增 1。

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new UpdateItemRequest { Key = new Dictionary<string, AttributeValue>() { { "Id", new AttributeValue { N = "121" } } }, ExpressionAttributeNames = new Dictionary<string, string>() { {"#Q", "Quantity"} }, ExpressionAttributeValues = new Dictionary<string, AttributeValue>() { {":incr",new AttributeValue {N = "1"}} }, UpdateExpression = "SET #Q = #Q + :incr", TableName = tableName }; var response = client.UpdateItem(request);

删除项目

DeleteItem 方法能删除表中的项目。

以下是使用低级 .NET SDK API 删除项目的步骤。

  1. 创建 AmazonDynamoDBClient 类的实例。

  2. 创建 DeleteItemRequest 类实例,提供所需的参数。

    要删除项目,需要表名和项目的主键。

  3. 通过提供您在之前步骤中创建的 DeleteItemRequest 对象,运行 DeleteItem 方法。

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string tableName = "ProductCatalog"; var request = new DeleteItemRequest { TableName = tableName, Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "201" } } }, }; var response = client.DeleteItem(request);

指定可选参数

您也可以使用 DeleteItemRequest 对象提供可选参数,如以下 C# 代码示例所示。它指定以下两个可选参数:

  • ExpressionAttributeValuesConditionExpression并指定只有当图书项目不再出版( InPublication 属性值为 false)时才能将其删除。

  • ReturnValues 参数,请求响应中的删除项目。

var request = new DeleteItemRequest { TableName = tableName, Key = new Dictionary<string,AttributeValue>() { { "Id", new AttributeValue { N = "201" } } }, // Optional parameters. ReturnValues = "ALL_OLD", ExpressionAttributeNames = new Dictionary<string, string>() { {"#IP", "InPublication"} }, ExpressionAttributeValues = new Dictionary<string, AttributeValue>() { {":inpub",new AttributeValue {BOOL = false}} }, ConditionExpression = "#IP = :inpub" }; var response = client.DeleteItem(request);

有关更多信息,请参阅DeleteItem

批处理写入:放置和删除多个项目

批量写入 是指批量放置和删除多个项目。BatchWriteItem 方法可让您通过一次 调用即可向一个或多个表中放置或从中删除多个项目。以下是使用低级 .NET SDK API 检索多个项目的步骤。

  1. 创建 AmazonDynamoDBClient 类的实例。

  2. 创建 BatchWriteItemRequest 类实例,描述所有放入和删除操作。

  3. 通过提供您在之前步骤中创建的 BatchWriteItemRequest 对象,运行 BatchWriteItem 方法。

  4. 处理响应。您应该检查一下响应是否返回未处理的请求项目。如果达到预置吞吐量配额或发生其他临时错误,就可能会出现这种情况。此外,DynamoDB 还对可在请求中指定的请求大小和操作数进行限制。如果超出这些限制,DynamoDB 会拒绝请求。有关更多信息,请参阅BatchWriteItem

以下 C# 代码示例演示了上述步骤。该示例创建了一个 BatchWriteItemRequest 执行以下写入操作:

  • Forum 表中放置一个项目。

  • Thread 表放置和删除项目。

代码运行 BatchWriteItem 执行批处理操作。

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string table1Name = "Forum"; string table2Name = "Thread"; var request = new BatchWriteItemRequest { RequestItems = new Dictionary<string, List<WriteRequest>> { { table1Name, new List<WriteRequest> { new WriteRequest { PutRequest = new PutRequest { Item = new Dictionary<string,AttributeValue> { { "Name", new AttributeValue { S = "Amazon S3 forum" } }, { "Threads", new AttributeValue { N = "0" }} } } } } } , { table2Name, new List<WriteRequest> { new WriteRequest { PutRequest = new PutRequest { Item = new Dictionary<string,AttributeValue> { { "ForumName", new AttributeValue { S = "Amazon S3 forum" } }, { "Subject", new AttributeValue { S = "My sample question" } }, { "Message", new AttributeValue { S = "Message Text." } }, { "KeywordTags", new AttributeValue { SS = new List<string> { "Amazon S3", "Bucket" } } } } } }, new WriteRequest { DeleteRequest = new DeleteRequest { Key = new Dictionary<string,AttributeValue>() { { "ForumName", new AttributeValue { S = "Some forum name" } }, { "Subject", new AttributeValue { S = "Some subject" } } } } } } } } }; response = client.BatchWriteItem(request);

要了解可工作的示例,请参阅 示例:使用低级 Amazon SDK for .NET API 进行批处理操作

批处理获取:获取多个项目

BatchGetItem 方法可让您检索一个或多个表中的多个项目。

注意

要检索单个项目,您可以使用 GetItem 方法。

以下是使用低级 Amazon SDK for .NET API 检索多个项目的步骤。

  1. 创建 AmazonDynamoDBClient 类的实例。

  2. 创建 BatchGetItemRequest 类实例,提供所需的参数。

    要检索多个项目,需要表名和主键值列表。

  3. 通过提供您在之前步骤中创建的 BatchGetItemRequest 对象,运行 BatchGetItem 方法。

  4. 处理响应。您应检查一下是否存在任何未处理的键,如果达到了预置吞吐量配额或发生某些其他临时错误,就可能会出现这种情况。

以下 C# 代码示例演示了上述步骤。该示例从两个表 ForumThread 检索项目。请求指定 Forum 表中两个项目和 Thread 表中三个项目。响应包括两个表中的项目。代码显示了如何处理响应。

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string table1Name = "Forum"; string table2Name = "Thread"; var request = new BatchGetItemRequest { RequestItems = new Dictionary<string, KeysAndAttributes>() { { table1Name, new KeysAndAttributes { Keys = new List<Dictionary<string, AttributeValue>>() { new Dictionary<string, AttributeValue>() { { "Name", new AttributeValue { S = "DynamoDB" } } }, new Dictionary<string, AttributeValue>() { { "Name", new AttributeValue { S = "Amazon S3" } } } } } }, { table2Name, new KeysAndAttributes { Keys = new List<Dictionary<string, AttributeValue>>() { new Dictionary<string, AttributeValue>() { { "ForumName", new AttributeValue { S = "DynamoDB" } }, { "Subject", new AttributeValue { S = "DynamoDB Thread 1" } } }, new Dictionary<string, AttributeValue>() { { "ForumName", new AttributeValue { S = "DynamoDB" } }, { "Subject", new AttributeValue { S = "DynamoDB Thread 2" } } }, new Dictionary<string, AttributeValue>() { { "ForumName", new AttributeValue { S = "Amazon S3" } }, { "Subject", new AttributeValue { S = "Amazon S3 Thread 1" } } } } } } } }; var response = client.BatchGetItem(request); // Check the response. var result = response.BatchGetItemResult; var responses = result.Responses; // The attribute list in the response. var table1Results = responses[table1Name]; Console.WriteLine("Items in table {0}" + table1Name); foreach (var item1 in table1Results.Items) { PrintItem(item1); } var table2Results = responses[table2Name]; Console.WriteLine("Items in table {1}" + table2Name); foreach (var item2 in table2Results.Items) { PrintItem(item2); } // Any unprocessed keys? could happen if you exceed ProvisionedThroughput or some other error. Dictionary<string, KeysAndAttributes> unprocessedKeys = result.UnprocessedKeys; foreach (KeyValuePair<string, KeysAndAttributes> pair in unprocessedKeys) { Console.WriteLine(pair.Key, pair.Value); }

指定可选参数

您也可以使用 BatchGetItemRequest 对象提供可选参数,如以下 C# 代码示例所示。示例从 Forum 表检索两个项目。其中指定了以下可选参数:

  • ProjectionExpression 参数,指定要检索的属性。

AmazonDynamoDBClient client = new AmazonDynamoDBClient(); string table1Name = "Forum"; var request = new BatchGetItemRequest { RequestItems = new Dictionary<string, KeysAndAttributes>() { { table1Name, new KeysAndAttributes { Keys = new List<Dictionary<string, AttributeValue>>() { new Dictionary<string, AttributeValue>() { { "Name", new AttributeValue { S = "DynamoDB" } } }, new Dictionary<string, AttributeValue>() { { "Name", new AttributeValue { S = "Amazon S3" } } } } }, // Optional - name of an attribute to retrieve. ProjectionExpression = "Title" } } }; var response = client.BatchGetItem(request);

有关更多信息,请参阅BatchGetItem