How to fetch specific attribute value from DynamoDB getItem in Java

Viewed 750

I am using Dynamodb Item - getItem API to get records from DynamoDB table. But it returns Item object and I want to retrieve specific attribute value from the Item object. How can we do it in Java? I couldn't find references.

Table table = dynamoDB.getTable(tableName);
Item item = table.getItem(hashKeyFieldName, hashKeyFieldValue);

The item contains the following fields: HashKey, TimeStamp, NumRetries

I want to get the specific NumRetries value from item above. Is it something that is possible? something like int numRetries = item.get("NumRetries");?

2 Answers

You should be able to do that with a Projection Expression:

GetItemSpec spec = new GetItemSpec().withPrimaryKey("primaryKey", primaryKey)
             .withProjectionExpression("HashKey,  TimeStamp, NumRetries");
Item outcome = table.getItem(spec);

A names map may be necessary.

You can use Projection Expressions to get certain attributes from an item but do keep in mind that using projection expressions does not reduce the usage and cost of RCUs that are used in retrieving the object.

Code example,

GetItemSpec spec = new GetItemSpec()
    .withPrimaryKey("YourPrimaryKey", value)
    .withProjectionExpression("NumRetries");

Item item = table.getItem(spec);

System.out.println(item.toJSONPretty());

More code examples can be found here.

Related