triplejjj
triplejjj

Reputation: 19

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.

Upvotes: 3

Views: 1218

Answers (2)

Jack Casey
Jack Casey

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

JD D
JD D

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

Related Questions