2
votes

I created a table in Amazon dynamodb with primary key Issue(String) which has data stored in it.I want to read the values from my table. I'm using the following code..

@DynamoDBTable(tableName="Incident")
 AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient();
 String tableName = "Incident";
 Table table = dynamoDBClient.getTable("Incident");
 Item getItem=dynamoDBClient.getItem();

I'm getting an error when calling the getTable method.... is it a predefined method just like createTable() or do we need to write our own..if so how? And also what method should be used to read all items in the table..? I used this link to write some of the code... http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaDocumentAPIItemCRUD.html#JavaDocumentAPIGetItem

I'm new to Java please help..

2

2 Answers

3
votes

Scan API can be used to get all the items from the table.

The scan should be done until LastEvaluatedKey is not null which is very important to get all the items. Otherwise, you will not get all the items if the table has many items i.e. the API will return 1 MB of data per scan.

A Scan operation performs eventually consistent reads by default, and it can return up to 1 MB (one page) of data.

Scan API

Map<String, AttributeValue> lastKeyEvaluated = null;
do {
    ScanRequest scanRequest = new ScanRequest()
        .withTableName("ProductCatalog")
        .withLimit(10)
        .withExclusiveStartKey(lastKeyEvaluated);

    ScanResult result = client.scan(scanRequest);
    for (Map<String, AttributeValue> item : result.getItems()){
        printItem(item);
    }
    lastKeyEvaluated = result.getLastEvaluatedKey();
} while (lastKeyEvaluated != null);
0
votes

Here is example how to read data using Scan API :

@Override
protected ArrayList<String> doInBackground(String... params) {
    String tableName = params[0];

    ArrayList<String> tempList = new ArrayList<String>();

    AmazonDynamoDBClient dynamoDBClient = new AmazonDynamoDBClient (
            new BasicAWSCredentials(Constants.ACCESS_KEY_ID,
                    Constants.SECRET_KEY));

    ScanRequest scanRequest = new ScanRequest()
        .withTableName(tableName);
        //.withAttributesToGet("name");
    com.amazonaws.services.dynamodb.model.ScanResult result = dynamoDBClient.scan(scanRequest);


    for (Map<String, AttributeValue> item : result.getItems()) {
        tempList.add(item.toString());
        //analizeItem(tempList, item);
    }

    return tempList;
}

Reference from programcreeks