OR condition in filter expression for dynamo db
Asked Answered
M

1

17

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.

Maccabees answered 20/12, 2016 at 19:57 Comment(1)
Either the attribute A or B is a partition key. In other words, what is your partition key and sort key of the table? Also, let me know the programming lang that you are using?Flavia
S
16

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

Skunk answered 28/12, 2016 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.