简体   繁体   English

Boto3:在 DynamoDB 中使用“NOT IN”进行扫描

[英]Boto3: use 'NOT IN' for Scan in DynamoDB

I've managed to make a filter expression for filtering items from Scan.我设法制作了一个过滤器表达式来过滤 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.我能否以某种方式将其从过滤转换为排除,因此我将获得除 ID 为 1、2、3 的用户之外的所有用户。

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 ~ .退房__invert__超载实施condition.py ,这是由触发~

The only way I have found so far is to use boto3.client instead of table and low-level syntax.到目前为止,我发现的唯一方法是使用 boto3.client 而不是 table 和低级语法。 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.因此,如果您知道更好的方法,请添加您的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM