Reputation: 19
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.
Upvotes: 3
Views: 1218
Reputation: 1836
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!
Upvotes: 3
Reputation: 8097
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
Upvotes: 2