更新 DynamoDB 中的字符串列

Update String column in DynamoDB

我是 DynamoDB 的新手,正在关注 tutorial 以实现基本的 CRUD 操作。

我有以下代码

public static void main(String ... args) throws Exception {
    
    //1. create client
    client = AmazonDynamoDBClientBuilder.standard()
            .withRegion(Regions.US_EAST_1)
            .build();

    //2. Create table
    String jobID="8aee43e5c44212040529fe11000117cdd0cb77eb";
    PutItemSpec putItemSpec = new PutItemSpec();
    putItemSpec.withItem(new Item().withPrimaryKey("jobid", jobID ).
            withString("type", "first").withBoolean("cancel", false));
    PutItemOutcome putItemOutcome = table.putItem(putItemSpec);
    System.out.println(putItemOutcome);

    //3. Read
    GetItemSpec spec = new GetItemSpec().withPrimaryKey("jobid", jobID);
    Item item = table.getItem(spec);
    System.out.println(item);

    //4.Update boolean
    UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("jobid", jobID)
            .withUpdateExpression("set cancel=:s")
            .withValueMap(new ValueMap().withBoolean(":s",true));
    UpdateItemOutcome updateItemOutcome = table.updateItem(updateItemSpec);

    //4. read updated bool
    item = table.getItem(spec);
    System.out.println(item);

    //5. update String breaks
    UpdateItemSpec updateItemSpec2 = new UpdateItemSpec().withPrimaryKey("jobid", jobID)
            .withUpdateExpression("set type=:s")
            .withValueMap(new ValueMap().withString(":s","updated"));
    UpdateItemOutcome updateItemOutcome2 = table.updateItem(updateItemSpec2);

    //4. read updated bool
    item = table.getItem(spec);
    System.out.println(item);
}}

在此代码中,Create 工作正常,getItem 获取数据。当我更新取消布尔列时,它工作正常并且 returns 更新的项目。但是,当我尝试将字符串列 type 更新为不同的值时,它会抛出以下异常。

Exception in thread "main" com.amazonaws.AmazonServiceException: Unable to unmarshall exception response with the unmarshallers provided (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: 4RHDOGACM1MOADU4N8RUPFMUJBVV4KQNSO5AEMVJF66Q9ASUAAJG; Proxy: null)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1862)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleServiceErrorResponse(AmazonHttpClient.java:1415)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1384)

AWS-SDK 版本为 1.12.153,JDK 版本为 17.0.1。此外,当我添加新的字符串列 type2 作为更新的一部分并使用另一个调用更新它时它可以工作。但是,作为创建的一部分添加的字符串列没有得到更新。

请让我知道我遗漏了什么?

谢谢!

单词 type 是许多 DynamoDB reserved words 中的一个。

不能在表达式中使用保留字。相反,您需要使用别名,然后向 DynamoDB 提供从别名到真实姓名的映射。例如,您可以通过 set #t=:s 指示别名,然后提供从 #ttype.

的映射

您的代码将如下所示:

UpdateItemSpec updateItemSpec2 =
    new UpdateItemSpec()
        .withPrimaryKey("jobid", jobID)
        .withUpdateExpression("set #t=:s")
        .withValueMap(new ValueMap().withString(":s","updated"))
        .withNameMap(new NameMap().with("#t","type"));