简体   繁体   English

Dynamodb 和 Boto3,在扫描中链接多个条件

[英]Dynamodb and Boto3, Chain Multiple Conditions in Scan

I'm looking for a way to create a scan request in Dynamodb with multiple FilterExpression conditions "ANDed" together.我正在寻找一种在 Dynamodb 中创建scan请求的方法,其中多个FilterExpression条件“与”在一起。

For example, we could scan a "fruit" database using this criteria:例如,我们可以使用以下标准扫描“水果”数据库:

criteria = {
  'fruit': 'apple', 
  'color': 'green',
  'taste': 'sweet'
}

I understand these could be concatenated into a string like so:我知道这些可以像这样连接成一个字符串:

FilterExpression = ' AND '.join([f"{k}=:{k}" for k, v in criteria.items()])
ExpressionAttributeValues = {f":{k}": {'S': v} for k, v in criteria.items()}

However this does not seem like the most elegant / pythonic approach.然而,这似乎不是最优雅/pythonic 的方法。

To be completely honest, I think what you have there is just fine although it is quite limited.老实说,我认为你在那里拥有的东西很好,尽管它非常有限。 This may be acceptable if what you are doing is very simple.如果您正在做的事情非常简单,这可能是可以接受的。

If you want to use a library to sort of act as an ORM for DynamoDB to make it easier to deal with storing/retrieving data using your own set of data classes instead of needing to transform that in/out of the boto responses, you should check out PynamoDB如果您想使用库作为 DynamoDB 的 ORM,以便使用您自己的数据类集更轻松地处理存储/检索数据,而不需要将其转换为输入/输出 boto 响应,您应该查看PynamoDB

Using reduce , it's possible to accomplish this behavior:使用reduce ,可以实现此行为:

from functools import reduce
from boto3.dynamodb.conditions import Key, And

FilterExpression=reduce(And, ([Key(k).eq(v) for k, v in criteria.items()]))

Hope this works for you!希望这对你有用!

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

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