简体   繁体   English

Java:无法删除 dynamodb 项目值

[英]Java: unable to delete dynamodb item value

I am trying to delete a field called "dog" from all of the items that resides on table animals, or that I use the following code:我试图从位于餐桌动物上的所有项目中删除一个名为“狗”的字段,或者我使用以下代码:

    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());

    }

But I am getting:但我得到:

    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

What am I doing wrong here?我在这里做错了什么?

by the way, I also tried:顺便说一句,我也试过:

   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);

But got the same exception.但得到了同样的例外。 (Also tried DELETE instead of REMOVE) (也试过删除而不是删除)

You are using the old V1 DynamoDB API, which is not best practice.您使用的是旧的 V1 DynamoDB API,这不是最佳实践。 It better practice to use the Amazon DynamoDB V2 Java API.最好使用 Amazon DynamoDB V2 Java API。

The AWS SDK for Java 2.x is a major rewrite of the version 1.x code base.适用于 Java 2.x 的 AWS 开发工具包是对 1.x 版代码库的主要重写。 It's built on top of Java 8+ and adds several frequently requested features.它建立在 Java 8+ 之上,并添加了几个经常请求的功能。 These include support for non-blocking I/O and the ability to plug in a different HTTP implementation at run time.其中包括对非阻塞 I/O 的支持以及在运行时插入不同 HTTP 实现的能力。

If you are not familiar with the AWS SDK for Java V2, see:如果您不熟悉适用于 Java V2 的 AWS 开发工具包,请参阅:

Get started with the AWS SDK for Java 2.x 开始使用适用于 Java 2.x 的 AWS 开发工具包

For this use case (which is modifying an item), the solution is to use the Enhanced Client, which lets you map Java objects to a table.对于此用例(修改项目),解决方案是使用 Enhanced Client,它允许您将 Java 对象映射到表。 For more information, see:有关更多信息,请参阅:

Mapping items in DynamoDB table s DynamoDB 表中映射项

Using the Enhanced Clint, you can modify an item with code like this:使用增强型 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 "";
    }
}

You can find this V2 example and others for Amazon DYnamoDB here:您可以在此处找到 Amazon DYnamoDB 的此 V2 示例和其他示例:

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

I found the solution for the issue, I cant believe I missed it.... Remember kids, its mandatory to look at the actual values when debugging!我找到了问题的解决方案,我不敢相信我错过了它......记住孩子们,调试时必须查看实际值!

So instead of using just:因此,而不是仅使用:

item.get("<property name>")

You need to explicitly ask for a String like so:您需要像这样明确要求一个字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM