Reputation: 5110
I want to query the dynamodb table with boolean or condition like SQL
e.g. Get me all the items where attribute1 = "no" or attribute2="no"
I tried with scanRequest.withScanFilter
but all the conditions are performed by doing boolean ANDing. How do I do boolean ORing.?
Upvotes: 24
Views: 33973
Reputation: 1135
You can also use brackets in a FilterExpression:
const params = {
TableName: process.env.PROJECTS_TABLE,
IndexName: 'teamId-createdAt-index',
KeyConditionExpression: 'teamId = :teamId',
ExpressionAttributeValues: {
':teamId': verifiedJwt.teamId,
':userId': verifiedJwt.userId,
':provider': verifiedJwt.provider
},
FilterExpression: 'attribute_exists(isNotDeleted) and ((attribute_not_exists(isPrivate)) or (attribute_exists(isPrivate) and userId = :userId and provider = :provider))'
};
Upvotes: 6
Reputation: 3614
You can set ConditionalOperator of your ScanRequest to "OR". The default value is "AND"
http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Scan.html
ScanRequest scanRequest = new ScanRequest("tableName");
scanRequest.setConditionalOperator(ConditionalOperator.OR);
Map<String, Condition> scanFilter = new HashMap<String, Condition>();
scanFilter.put("attribute1", new Condition().withAttributeValueList(new AttributeValue("no")).withComparisonOperator(ComparisonOperator.EQ));
scanFilter.put("attribute2", new Condition().withAttributeValueList(new AttributeValue("no")).withComparisonOperator(ComparisonOperator.EQ));
scanRequest.setScanFilter(scanFilter);
ScanResult scanResult = dynamo.scan(scanRequest);
for(Map<String, AttributeValue> item : scanResult.getItems()) {
System.out.println(item);
}
Upvotes: 9
Reputation: 5143
If you happen to know the HashKey
value, another option would be to use QUERY and a FilterExpression. Here is an example with the Java SDK:
Table table = dynamoDB.getTable(tableName);
Map<String, Object> expressionAttributeValues = new HashMap<String, Object>();
expressionAttributeValues.put(":x", "no");
expressionAttributeValues.put(":y", "no");
QuerySpec spec = new QuerySpec()
.withHashKey("HashKeyAttributeName", "HashKeyValueHere")
.withFilterExpression("attribute1 = :x or attribute2 = :y")
.withValueMap(expressionAttributeValues);
ItemCollection<QueryOutcome> items = table.query(spec);
Iterator<Item> iterator = items.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().toJSONPretty());
}
See Specifying Conditions with Condition Expressions for more details.
Upvotes: 5