问题
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.
回答1:
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.
回答2:
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 of in condition.py, which is triggered by ~
.
来源:https://stackoverflow.com/questions/50370984/boto3-use-not-in-for-scan-in-dynamodb