简体   繁体   中英

Java AWS DynamoDB how to increment number

I'm trying to add 1 to a number, and then get the new number back.

I can't get my UpdateItemSpec right. Please help. Every example out there seems to show something different and none of it is working.

Here is my code:

AmazonDynamoDBClient dbClient = new AmazonDynamoDBClient(
            new BasicAWSCredentials("SECRET", "SECRET")
);
dbClient.setRegion(Region.getRegion(Regions.fromName("us-west-1")));
DynamoDB dynamoDB = new DynamoDB(dbClient);
Table table = dynamoDB.getTable("NumTable");

GetItemSpec spec = new GetItemSpec()
  .withPrimaryKey("PKey","OrderNumber");

Item item = table.getItem(spec);
logger.info(item.toJSONPretty());

UpdateItemSpec updateItemSpec = new UpdateItemSpec()
            .withPrimaryKey("Pkey",
                    "OrderNumber")
            .withReturnValues("UPDATED_NEW")
            .withUpdateExpression("ADD #k :incr")
            .withNameMap(new NameMap().with("#k", "NumVal"))
            .withValueMap(
                    new ValueMap()
                            .withNumber(":incr", 1));
                        //.withString(":incr", "{N:\"1\"}"));
                        //I've tried a million other ways too!


UpdateItemOutcome outcome = table.updateItem(updateItemSpec);
logger.info(outcome.getItem().toJSONPretty());

Console shows the first get part working:

Sat Nov 09 00:46:07 UTC - 2019-11-09 00:46:07 f1475303-7585-4804-8a42-2e0a9b16b1dc INFO Commission:88 - {
Sat Nov 09 00:46:07 UTC - "NumVal" : 200000,
Sat Nov 09 00:46:07 UTC - "PKey" : "OrderNumber"
Sat Nov 09 00:46:07 UTC - }

But the update part gives this error (among others):

Sat Nov 09 00:46:08 UTC - The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: 8TPDT2EVMC0G0GF3IFK7SU6777VV4KQNSO5AEMVJF66Q9ASUAAJG): com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException com.amazonaws.services.dynamodbv2.model.AmazonDynamoDBException: The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: 8TPDT2EVMC0G0GF3IFK7SU6777VV4KQNSO5AEMVJF66Q9ASUAAJG) at [........]

I really feel like the key element does match the schema:'(

Here is a picture from my AWS console:

在此处输入图像描述

Your implementation looks fine to me. The error is because of typo error in your UpdateItemSpec code.

UpdateItemSpec updateItemSpec = new UpdateItemSpec()
            .withPrimaryKey("Pkey",
                    "OrderNumber")

The typo is "Pkey". It should be "PKey", which is why it works in GetItemSpec code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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