Search code examples
javaamazon-dynamodbdynamo-local

Retrieve selected data from DynamoDB local in java


I have created a table in my local dynamoDB. The fields are,

id (N)
name (S)
school (S)
classname (S)

Now I want to retrieve all the records for which school equals to "xschool" and print.

Tried the below code but it gives me an error in the query,

QuerySpec spec = new QuerySpec().withProjectionExpression("sid, classname, school")
            .withKeyConditionExpression("school = :v_school").
            withValueMap(new ValueMap().withString(":v_school", "abcschool"));

        ItemCollection<QueryOutcome> items = table.query(spec);

        Iterator<Item> iterator = items.iterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next().toJSONPretty());
        }

Any suggestions for this as I'm new to dynamoDB.


Solution

  • AmazonDynamoDB dynamoDBClient = createClient();
    DynamoDB dynamoDB = new DynamoDB(dynamoDBClient);        
    
    String tableName = "student";
    Table table = dynamoDB.getTable(tableName);
    
    Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
    expressionAttributeValues.put(":sc", schoolname);
    
    ItemCollection<ScanOutcome> items = table.scan("school = :sc", // FilterExpression
        "sid, school, firstname, classname", // ProjectionExpression
        null, // ExpressionAttributeNames - not used in this example
        expressionAttributeValues);
    
    Iterator<Item> iterator = items.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next().toJSONPretty());
    }
    

    Try this, I think this will work for you