Search code examples
aws-lambdaamazon-dynamodbdynamodb-queries

Lambda DynamoDB "x and (y or z)" Query


I need to create a dynamoDB query that fetches results based on an index, but only if 1 of 2 conditions are met.

Something like this:

KeyConditionExpression: '#list = :listID and (#owner = :userID or #collab = :userID)'

list is indexed.

I understand if I had only 1 extra param to use, I could add that as the sort key on the index, but what when I need 2?

Do I need to add indexes for both owner and collab, but then what do I put as the IndexName for the query?


Solution

  • You cannot do an OR expression on keys efficiently. You should model your data in such a way that the partition key and sort key model the majority of the evaluated data, then you can use a FilterExpression to refine the remainder of the data.

    Or simply apply it like this:

    KeyConditionExpression: '#list = :listID'
    FilterExpression: '#owner = :userID or #collab = :userID)'