Search code examples
amazon-web-servicesamazon-dynamodbdynamodb-queriesamazon-dynamodb-index

Query all users in DynamoDB with a single-table design


I have a simple single-table design that I want to keep flexible for the future, I currently have 2 entity types: users and videos. Users have a 1:n relationship to videos.

The table's partition key is pk and sort key is sk.

Users: pk=u#<id> and sk=u#<id>, entityType: user

Videos: pk=u#<id> and sk=v#<id>, entityType: video

If I want to fetch all users, does it make sense to create a GSI with PK=entityType and SK=sk?


Solution

  • No, because then all user writes will go to the same PK which isn’t ideal. Instead, setup a GSI with a GSI1PK holding your user ID and you can do a scan against it. Project in the essential attributes. Only set the GSI1PK for user entity types so it’s a sparse GSI.