Java: 无法删除 dynamodb 项目值

Java: unable to delete dynamodb item value

我正在尝试从 table 动物的所有项目中删除一个名为“dog”的字段,或者我使用以下代码:

    Table table= dynamoDB.getTable("animals");
    ScanRequest scanRequest = new ScanRequest().withTableName("animals");
    ScanResult result = client.scan(scanRequest);


    for (Map<String, AttributeValue> item : result.getItems()){

        table.updateItem(new PrimaryKey("<Primary partition key name>", item.get("<Primary partition key name>"),"<Primary sort key name>", item.get("<Primary sort key name>")), 
new AttributeUpdate("dog").delete());

    }

但我得到:

    Exception in thread "main" java.lang.RuntimeException: value type: class com.amazonaws.services.dynamodbv2.model.AttributeValue
.
.
.
    Caused by: java.lang.UnsupportedOperationException: value type: class com.amazonaws.services.dynamodbv2.model.AttributeValue

我做错了什么?

对了,我也试过了:

   UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                    .withPrimaryKey("<Primary partition key name>", item.get("<Primary partition key name>"),"<Primary sort key name>", item.get("<Primary sort key name>"))
                    .withUpdateExpression("REMOVE dog");
            table.updateItem(updateItemSpec);

但遇到了同样的异常。 (还尝试使用 DELETE 而不是 REMOVE)

您使用的是旧版 V1 DynamoDB API,这不是最佳做法。最好使用 Amazon DynamoDB V2 Java API.

适用于 Java 2.x 的 AWS 开发工具包是对版本 1.x 代码库的重大重写。它建立在 Java 8+ 之上,并添加了几个经常请求的功能。其中包括对非阻塞 I/O 的支持以及在 运行 时间插入不同 HTTP 实现的能力。

如果您不熟悉 Java V2 的 AWS 开发工具包,请参阅:

Get started with the AWS SDK for Java 2.x

对于此用例(正在修改项目),解决方案是使用增强型客户端,它可以让您将 Java 对象映射到 table。欲了解更多信息,请参阅:

Mapping items in DynamoDB tables

使用 Enhanced Clint,您可以使用如下代码修改项目:

    package com.example.dynamodb;


import software.amazon.awssdk.enhanced.dynamodb.DynamoDbEnhancedClient;
import software.amazon.awssdk.enhanced.dynamodb.DynamoDbTable;
import software.amazon.awssdk.enhanced.dynamodb.Key;
import software.amazon.awssdk.enhanced.dynamodb.TableSchema;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbBean;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbPartitionKey;
import software.amazon.awssdk.enhanced.dynamodb.mapper.annotations.DynamoDbSortKey;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import java.time.Instant;


/*
 * Prior to running this code example, create an Amazon DynamoDB table named Customer with these columns:
 *   - id - the id of the record that is the key
 *   - custName - the customer name
 *   - email - the email value
 *   - registrationDate - an instant value when the item was added to the table
 *  Also, ensure that you have setup your development environment, including your credentials.
 *
 * For information, see this documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */

public class EnhancedModifyItem {

    public static void main(String[] args) {


        String usage = "Usage:\n" +
                "    UpdateItem <key> <email> \n\n" +
                "Where:\n" +
                "    key - the name of the key in the table (id120).\n" +
                "    email - the value of the modified email column.\n" ;

       if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
       }

        String key = args[0];
        String email = args[1];
        Region region = Region.US_EAST_1;
        DynamoDbClient ddb = DynamoDbClient.builder()
                .region(region)
                .build();

        DynamoDbEnhancedClient enhancedClient = DynamoDbEnhancedClient.builder()
                .dynamoDbClient(ddb)
                .build();

        String updatedValue = modifyItem(enhancedClient,key,email);
        System.out.println("The updated name value is "+updatedValue);
        ddb.close();
    }


    public static String modifyItem(DynamoDbEnhancedClient enhancedClient, String keyVal, String email) {
        try {
            //Create a DynamoDbTable object
            DynamoDbTable<Customer> mappedTable = enhancedClient.table("Customer", TableSchema.fromBean(Customer.class));

            //Create a KEY object
            Key key = Key.builder()
                    .partitionValue(keyVal)
                    .build();

            // Get the item by using the key and update the email value.
            Customer customerRec = mappedTable.getItem(r->r.key(key));
            customerRec.setEmail(email);
            mappedTable.updateItem(customerRec);
            return customerRec.getEmail();

        } catch (DynamoDbException e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
        return "";
    }
}

您可以在此处找到此 V2 示例和其他适用于 Amazon DYnamoDB 的示例:

https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javav2/example_code/dynamodb

我找到了问题的解决方案,真不敢相信我错过了.... 记住孩子们,调试时必须查看实际值!

所以不要只使用:

item.get("<property name>")

您需要像这样明确要求一个字符串:

item.get("<property name>").getS()