Niklas
Niklas

Reputation: 1331

DynamoDB how to use a filter expression on a bool value

How do I filter a dynamoDB table with an expression on a bool value. I can filter successfully on an Int or String value. But even in the web console when trying to create a filter expression on a bool value it won't give any results back?

I'm trying this from Swift on iOS as well, but the fact that it doesn't even work int he web interface makes me wonder how to at all achieve this.

If I filter on an Int it works, i.e.

    let queryExpression = AWSDynamoDBQueryExpression()
    queryExpression.rangeKeyConditionExpression = "age = :val"
    queryExpression.expressionAttributeValues = [":val": 30]

But if I try on an Bool it comes back with nothing.

    let queryExpression = AWSDynamoDBQueryExpression()
    queryExpression.rangeKeyConditionExpression = "enabled = :val"
    queryExpression.expressionAttributeValues = [":val": true]

I've also tried a 0 or a 1 in place of true, or a string as in "true".

However, this filtering on an Bool doesn't even work in the AWS web interface. So it's not a Swift thing it seems. Maybe it's not possible, but seems odd.

Turns out I was confused here, filterExpression works fine.

   let scanExpression = AWSDynamoDBScanExpression()
   scanExpression.filterExpression = "disabled = :val"
   scanExpression.expressionAttributeValues = [":val": false]

Upvotes: 5

Views: 10359

Answers (1)

Sernst
Sernst

Reputation: 524

The documentation isn't very clear about this, but it is not possible to create a table in DynamoDB with a boolean hash or range key. The hash and range keys can only be of types string (S), numeric (N), or binary (B). If you try to create a table with a boolean (BOOL) range key such as:

create_table(
    AttributeDefinitions=[
        {'AttributeName': 'something', 'AttributeType': 'S'},
        {'AttributeName': 'enabled', 'AttributeType': 'BOOL'}
    ],
    TableName='example',
    KeySchema=[
        {'AttributeName': 'something', 'KeyType': 'HASH'},
        {'AttributeName': 'enabled', 'KeyType': 'RANGE'},
    ]    
    ...
)

the call will fail on the requirement that the 'enabled' range key be of type 'S', 'N' or 'B'.

If you want to effectively store a boolean in the range key, you should use the numeric type and assign 0 and 1 values, which can be filtered as you've already demonstrated.

If you have a boolean value that is not a hash or range key, you can filter it with a FilterExpression instead of a RangeKeyConditionExpression as described in the FilterExpression documentation.

Upvotes: 2

Related Questions