Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update item in DynamoDB using Java

I want to update specific Item(Only One data from row),

How can I update item in DynamoDB.?

login_id is my primary key. I pass login_id and other boolean value. I want to set boolean value true according to that login-id.

How can I do that?

I tried this code.

LinkedHashMap inputHashMap = (LinkedHashMap) input;

        login_id = (String) inputHashMap.get("login_id");
        isUserVerified = (Boolean) inputHashMap.get("isUserVerified");

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

        Table tableUserDetails = dynamoDB.getTable(USER_DETAILS_TABLE);
        Table tableOtpStatus = dynamoDB.getTable(OTP_DETAILS_TABLE);

        UpdateItemSpec updateItemSpec = new UpdateItemSpec().withPrimaryKey("login_id", login_id);

        try{

            UpdateItemOutcome outcome = tableUserDetails.updateItem(updateItemSpec);
            System.out.println("UpdateItem succeeded:\n" + outcome.getItem().toJSONPretty());
        }catch(Exception e){
            System.err.println(e.getMessage());
        }

While executing above code I got below exception.

The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException;
like image 238
Chirag Savsani Avatar asked Mar 12 '23 08:03

Chirag Savsani


1 Answers

Looks like you're missing the update expression. Assuming isUserVerified is part of the primary key, it should be something like:

UpdateItemSpec updateItemSpec = new UpdateItemSpec()
      .withPrimaryKey("login_id", login_id)
      .withUpdateExpression("set isUserVerified = :val")
      .withValueMap(new ValueMap()
         .withBoolean(":val", true));

If isUserVerified not part of the key then just remove it from the .withPrimaryKey() statement.

You can find more here.

like image 147
Benny Bauer Avatar answered Mar 26 '23 10:03

Benny Bauer