Myroslav Hryshyn
Myroslav Hryshyn

Reputation: 726

Boto3: use 'NOT IN' for Scan in DynamoDB

I've managed to make a filter expression for filtering items from Scan. Smth like:

users = [1, 2, 3]
table.scan(
    FilterExpression=Attr('user_id').is_in(users) 
)

Can I somehow convert it from filtering to excluding, so I will get all users except those with ids 1, 2, 3.

Upvotes: 3

Views: 4220

Answers (2)

Ricardo Nolde
Ricardo Nolde

Reputation: 34285

You can do this easily by using the ~ operator:

users = [1, 2, 3]
table.scan(
    FilterExpression=~Attr('user_id').is_in(users)
)

Check out the __invert__ overload implementation in condition.py, which is triggered by ~.

Upvotes: 4

Myroslav Hryshyn
Myroslav Hryshyn

Reputation: 726

The only way I have found so far is to use boto3.client instead of table and low-level syntax. Smth like this:

lst_elements = ''
attr_elements = {}
for id in user_ids:
    lst_element += 'user' + str(id)
    attr_elements['user' + str(id)] = id

client.scan(
    TableName='some_table_name',
    FilterExpression="NOT (user_id IN ({}))".format(lst_element[:-1]),
    ExpressionAttributeValues=attr_elements
)

This solution works fine for me but looks really complicated. So if you know a better way to do it, please add your answer.

Upvotes: 2

Related Questions