简体   繁体   中英

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.

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.

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

Using reduce , it's possible to accomplish this behavior:

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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