简体   繁体   中英

How to fetch specific attribute value from DynamoDB getItem in Java

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.

import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
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"); ?

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 .

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