Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OR condition in filter expression for dynamo db

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.

like image 352
Sumit Gulati Avatar asked Dec 20 '16 19:12

Sumit Gulati


People also ask

Can conditional operations be used in a DynamoDB query?

Yes, like all the other database management systems, DynamoDB also supports all the conditional operators, User can specify a condition that is satisfied for a put, update, or delete operation to work on an item.

What is key condition expression in DynamoDB?

For more information, see Using expressions in DynamoDB. KeyConditions are the selection criteria for a Query operation. For a query on a table, you can have conditions only on the table primary key attributes. You must provide the partition key name and value as an EQ condition.

Does DynamoDB support Boolean?

DynamoDB supports the Java Set , List , and Map collection types. The following table summarizes how these Java types map to the DynamoDB types. BOOL (Boolean type), 0 or 1. S (string type).


1 Answers

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

like image 62
gitesh.tyagi Avatar answered Oct 24 '22 16:10

gitesh.tyagi