Dynamodb 简明教程

DynamoDB - Update Items

在 DynamoDB 中更新一个项目主要包括为项目指定完整的主键和表名。您需要修改的每个属性都需要一个新值。该操作使用 UpdateItem ,它修改现有项目或在发现缺少项目时创建它们。

更新中,您可能希望通过在操作之前和之后显示原始值和新值来跟踪更改。UpdateItem 使用 ReturnValues 参数来实现此目的。

Note − 该操作不报告预留单元消耗,但您可以使用 ReturnConsumedCapacity 参数。

使用 GUI 控制台、Java 或任何其他工具执行此任务。

How to Update Items Using GUI Tools?

导航到控制台。在左侧的导航窗格中,选择 Tables 。选择所需的表,然后选择 Items 选项卡。

update items using gui tools

选择希望更新的项目,然后选择 Actions | Edit

choose item

Edit Item 窗口中修改任何必要的属性或值。

Update Items Using Java

在项目更新操作中使用 Java 就需要创建一个表类实例,并调用其 updateItem 方法。然后,指定项目的键并提供详细的 UpdateExpression 属性修改。

以下是一个相同的示例 −

DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
   new ProfileCredentialsProvider()));

Table table = dynamoDB.getTable("ProductList");

Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#M", "Make");
expressionAttributeNames.put("#P", "Price
expressionAttributeNames.put("#N", "ID");

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val1",
   new HashSet<String>(Arrays.asList("Make1","Make2")));
expressionAttributeValues.put(":val2", 1);       //Price

UpdateItemOutcome outcome =  table.updateItem(
   "internalID",                                 // key attribute name
   111,                                          // key attribute value
   "add #M :val1 set #P = #P - :val2 remove #N", // UpdateExpression
   expressionAttributeNames,
   expressionAttributeValues);

updateItem 方法还允许指定条件,可以在以下示例中看到 −

Table table = dynamoDB.getTable("ProductList");
Map<String, String> expressionAttributeNames = new HashMap<String, String>();
expressionAttributeNames.put("#P", "Price");

Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":val1", 44);  // change Price to 44
expressionAttributeValues.put(":val2", 15);  // only if currently 15

UpdateItemOutcome outcome = table.updateItem (new PrimaryKey("internalID",111),
   "set #P = :val1",                        // Update
   "#P = :val2",                            // Condition
   expressionAttributeNames,
   expressionAttributeValues);

Update Items Using Counters

DynamoDB 允许原子计数器,这意味着可以使用 UpdateItem 递增/递减属性值,而不会影响其他请求;此外,计数器总是更新。

以下是解释如何执行此操作的示例。

Note − 以下示例可能假设之前创建过数据源。在尝试执行之前,获取支持库并创建必要的数据源(具有所需特性的表,或其他参考源)。

此示例还使用 Eclipse IDE、AWS 凭据文件和 Eclipse AWS Java 项目中的 AWS 工具包。

package com.amazonaws.codesamples.document;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
import com.amazonaws.services.dynamodbv2.document.DeleteItemOutcome;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;

import com.amazonaws.services.dynamodbv2.document.UpdateItemOutcome;
import com.amazonaws.services.dynamodbv2.document.spec.DeleteItemSpec;
import com.amazonaws.services.dynamodbv2.document.spec.UpdateItemSpec;
import com.amazonaws.services.dynamodbv2.document.utils.NameMap;
import com.amazonaws.services.dynamodbv2.document.utils.ValueMap;
import com.amazonaws.services.dynamodbv2.model.ReturnValue;

public class UpdateItemOpSample {
   static DynamoDB dynamoDB = new DynamoDB(new AmazonDynamoDBClient(
      new ProfileCredentialsProvider()));
   static String tblName = "ProductList";

   public static void main(String[] args) throws IOException {
      createItems();
      retrieveItem();

      // Execute updates
      updateMultipleAttributes();
      updateAddNewAttribute();
      updateExistingAttributeConditionally();

      // Item deletion
      deleteItem();
   }
   private static void createItems() {
      Table table = dynamoDB.getTable(tblName);
      try {
         Item item = new Item()
            .withPrimaryKey("ID", 303)
            .withString("Nomenclature", "Polymer Blaster 4000")
            .withStringSet( "Manufacturers",
            new HashSet<String>(Arrays.asList("XYZ Inc.", "LMNOP Inc.")))
            .withNumber("Price", 50000)
            .withBoolean("InProduction", true)
            .withString("Category", "Laser Cutter");
            table.putItem(item);

         item = new Item()
            .withPrimaryKey("ID", 313)
            .withString("Nomenclature", "Agitatatron 2000")
            .withStringSet( "Manufacturers",
            new HashSet<String>(Arrays.asList("XYZ Inc,", "CDE Inc.")))
            .withNumber("Price", 40000)
            .withBoolean("InProduction", true)
            .withString("Category", "Agitator");
            table.putItem(item);
      } catch (Exception e) {
         System.err.println("Cannot create items.");
         System.err.println(e.getMessage());
      }
   }
   private static void updateAddNewAttribute() {
      Table table = dynamoDB.getTable(tableName);
      try {
         Map<String, String> expressionAttributeNames = new HashMap<String, String>();
         expressionAttributeNames.put("#na", "NewAttribute");
         UpdateItemSpec updateItemSpec = new UpdateItemSpec()
            .withPrimaryKey("ID", 303)
            .withUpdateExpression("set #na = :val1")
            .withNameMap(new NameMap()
            .with("#na", "NewAttribute"))
            .withValueMap(new ValueMap()
            .withString(":val1", "A value"))
            .withReturnValues(ReturnValue.ALL_NEW);
            UpdateItemOutcome outcome =  table.updateItem(updateItemSpec);

         // Confirm
         System.out.println("Displaying updated item...");
         System.out.println(outcome.getItem().toJSONPretty());
      } catch (Exception e) {
         System.err.println("Cannot add an attribute in " + tableName);
         System.err.println(e.getMessage());
      }
   }
}