Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDb query with filter expression in Java

I have a DynamoDb table named school-data in AWS. Below is the existing code to get all the school with a school's name:

private DynamoDBQueryExpression<School> createQueryBySchoolName(String schoolName) {
    String matchSchoolName = "schoolName = :schoolName";
    Map<String, AttributeValue> schoolNames = new HashMap<>();
    schoolNames.put(":schoolName", new AttributeValue().withS(schoolName));

    return new DynamoDBQueryExpression<School>()
            .withIndexName("schoolName-index")
            .withKeyConditionExpression(matchSchoolName)
            .withExpressionAttributeValues(schoolNames)
            .withConsistentRead(false);
}

The above query works fine. But Now I need to fetch all schools with a particular school name and their address . So, below are the 3 columns in the table:

id   schoolName  details

The data in details column looks like below:

{
"zone": "North",
"type": "Convent",
"address": {
    "id": "138",
    "street1": "123 Street",
    "street2": "456 Road"
}
}

So, I need to fetch all the schools with name 'ABC' and address street1 as '123 Street'. So, I updated the above query as below:

private DynamoDBQueryExpression<School> createQueryBySchoolName(String schoolName) {
    String matchSchoolName = "schoolName = :schoolName";
    Map<String, AttributeValue> schoolNames = new HashMap<>();
    schoolNames.put(":schoolName", new AttributeValue().withS(schoolName));
    schoolNames.put(":streetName", new AttributeValue().withS("123 Street"));


    return new DynamoDBQueryExpression<School>()
            .withIndexName("schoolName-index")
            .withKeyConditionExpression(matchSchoolName)
            .withFilterExpression("details.address.street1 = :streetName")
            .withExpressionAttributeValues(schoolNames)
            .withConsistentRead(false);
}

But, this returns no data. Can you please let me know what am I doing wrong?

like image 225
T Anna Avatar asked May 13 '20 13:05

T Anna


1 Answers

You need to set HashKeyValues for the DynamoDBQueryExpression and add the page limit

private DynamoDBQueryExpression<School> createQueryBySchoolName(String schoolName) {
String matchSchoolName = "schoolName = :schoolName";
Map<String, AttributeValue> schoolNames = new HashMap<>();
schoolNames.put(":schoolName", new AttributeValue().withS(schoolName));
schoolNames.put(":streetName", new AttributeValue().withS("123 Street"));


return new DynamoDBQueryExpression<Voucher>()
        .withHashKeyValues(schoolName)
        .withIndexName("schoolName-index")
        .withKeyConditionExpression(matchSchoolName)
        .withFilterExpression("details.address.street1 = :streetName")
        .withExpressionAttributeValues(schoolNames)
        .withConsistentRead(false)
        .withLimit(pPageSize);

}

like image 194
Vijay Kharwar Avatar answered Sep 29 '22 09:09

Vijay Kharwar