OR condition in filter expression for dynamo db

Sumit Gulati picture Sumit Gulati · Dec 20, 2016 · Viewed 13.2k times · Source

I have a use case where I need to query dynamo db programatically using dynamo db query expression. e.x suppose there is two attributes for the A and B and I want a filter expression like (A='Test' OR A ='Test1') and B='test2'.

I searched related to this but din't find useful resource. I am new to dynamo db.

Answer

gitesh.tyagi picture gitesh.tyagi · Dec 28, 2016

Thats how you do it in java

Table table = dynamoDB.getTable(tableName);
QuerySpec spec = new QuerySpec()
   // .withKeyConditionExpression("partitionKey = :id and sortKey > :range") // In case filter expression is on key attributes
    .withFilterExpression("(A = :a1 or A = :a2) and B = :b")
    .withValueMap(new ValueMap()
        //.withString(":id", "Partition key value")
        //.withString(":range", 100)
        .withString(":a1", "Test")
        .withString(":a2", "Test1")
        .withString(":b", "test2"))
   // .withConsistentRead(true);

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

If your A and B are key attributes you specify them in KeyConditionExpression else everything goes in FilterExpression.

Main Difference is Key expressions are applied on key attributes as name suggests and records getting fetched due to it is what you get charged for, while filter expression comes free and is applied after fetching those records to return you only matching the filter condition records.

To understand more read http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#FilteringResults

http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html