Is it possible to filter a DynamoDB query result in python?

Viewed 2513

The format of my data looks like this

{
  ID:'some uuid'
  Email:'some@email.com',
  Tags=[tag1,tag2,tag3...],
  Content:' some content'
}

The partition key is ID and the sort key is Email I created a secondary index of email which is "email_index" if I only want to query by Email, Now I want to query data both by Email and by a specific tag For example I want to find all data that Email='some@email.com' and Tags contains 'tag2', I want to first query by "email_index"

result=table.query(
            IndexName='EmailIndex',
            KeyConditionExpression='Email=:email',
            ExpressionAttributeValues={
                ':email':'some@email.com'
            }
)['Items']

then scan the result with Attr('Tags').contains('tag2') So is it possible to do both at the same time? Or I have to write a loop to filter query results in Python?

1 Answers

Tags can be a tricky use case for DynamoDB.

One option is to use a FilterExpression on your query operation

result=table.query(
            IndexName='EmailIndex',
            KeyConditionExpression='Email=:email',
            FilterExpression: 'contains(Tags, :tag)',
            ExpressionAttributeValues={
                ':email':'some@email.com',
                ':tag': 'tag1'
            }
)['Items']

Another option, as you've outlined, is to do the check in your application code.

If this isn't flexible enough for your use case, you may want to look into a more robust search solution like Elasticsearch.

Related