Boto3: use 'NOT IN' for Scan in DynamoDB

拟墨画扇 提交于 2020-05-15 21:45:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!