Problem:
You can query or scan data from dynamodb. Try different ways to scan from DynamoDB.
Solution Summary:
You can do DynamoDB scan in two ways:
- Calling scan on a Table object.
- Calling scan on the client object of type AmazonDynamoDB.
Prerequisites:
This is a continuation to lab: Create Table, Load Data And Write Cleanup Code in Java Spring For DynamoDB
Solution Steps:
Calling scan on a Table object can be done as follows:
@Autowired
AmazonDynamoDB client;
…
System.out.println("Scaning!!!");
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable(demoTableName);
ScanSpec scanSpec = new ScanSpec();
List<Map<String, String>> finalList = new ArrayList<>();
Map<String, String> rowMap = new HashMap<>();
ItemCollection<ScanOutcome> scanItems = table.scan(scanSpec);
Iterator<Item> scanItemsIterator = scanItems.iterator();
while (scanItemsIterator.hasNext()) {
Item item = scanItemsIterator.next();
String name = item.getString("Name");
String desig = item.getString("Designation");
System.out.println("adding "+name + " as "+ desig);
rowMap.put(name, desig);
finalList.add(rowMap);
}
System.out.println("SCAN LIST RESULT:");
System.out.println(finalList);
Calling scan on the client object of type AmazonDynamoDB can be done as:
@Autowired
AmazonDynamoDB client;
…
System.out.println("Scanning with ScanRequest");
ScanRequest scanRequest = new ScanRequest()
.withProjectionExpression("#Name, Designation")
.withTableName(demoTableName);
scanRequest.withProjectionExpression("Designation");
System.out.println(scanRequest.getProjectionExpression());
ScanResult result = client.scan(scanRequest);
final List<Map<String, AttributeValue>> resultItems = result.getItems();
final List<Map<String, String>> rowMaps = new ArrayList<>();
resultItems.forEach(map -> {
final Map<String, String> m = map.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, v -> v.getValue().getS()));
rowMaps.add(m);
});
System.out.println("SCAN LIST RESULT:");
System.out.println(rowMaps);
Both approaches have their own merits; for instance, first approach gives more flexibility, but will require an extra call to dynamodb to first get the table object and then do the query.
Go through the documentation and decide on the best approach suitable for your case.
Recent comments