Search code examples
dynamodb-queries

Fetch all records which matches to non key attribute dynamoDB without using SCAN


I need to fetch all records if boolean value true. Example in DynamoDB I have 3 attributes. (attribute1-PK and attribute2-SK). Now based on non key attribute 3 need to fetch all records if attribute3=true.

attribute1   attribute2     attribute3
test            1234           false
test1           1235           true
test2           1236           true
test3           1237           false

Please provide me which is the best approach to use. I saw using SCAN it works but its too costly to use scan. Need alternative solution.


Solution

  • This is a usecase for Global Secondary Indexes (GSI) in DynamoDB.

    https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html

    Add a GSI on attribute3 called attribute3-index and use the DynamoDB query API with the IndexName="attribute3-index" (syntax may vary depending on whether you use AWS CLI or SDK).

    Here are some example API calls: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GCICli.html

    You might also consider a Local Secondary Index, depending on your access patterns. However, unlike GSIs, Local Secondary Indexes must be created at the time of table creation.

    https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-indexes-general.html

    A good practice is to plan access patterns for the table before its creation, allowing you to make the best decisions about what indexes to create.