2
votes

Let's say I already have partition key on a table and I'm adding a global secondary index. What would be the point of creating this GSI without a sort key? The more I read about GSI, AWS seems to stress the flexibility GSIs have regarding specifying your own partition key and sort key. I'm not quite sure the use of adding a GSI without specifying a sort key.

3

3 Answers

10
votes

GSI's with only a Partition Key allow you to query the DynamoDB table using the attribute you chose to be the Partition Key.

For example, if you have a table that has three attributes:

  1. userId
  2. username
  3. updatedAt

If your table's Primary Key consists of let's say userId as the Partition Key and updatedAt as the Sort Key (which will allow you to query the table for the list of users sorted by updatedAt date), then you can add a GSI with only the username as the Partition Key to query that same table for a specific username.

3
votes

GSI gives you the ability to use an Index key - giving you the ability to access a key very fast O(n) on your table.

0
votes

Typically, you would want to have a sort key as you get indexing on base table itself. However, when creating the table, the sort key was not created, then you cannot create it retrospectively. In that case, you can create a GSI (of course, you would create GSI's normally as well for indexing other attributes). Also, if your GSI hash key is different from main table hash key, then also sort key won't work and you need a GSI.

GSI's are stored in another table (managed by DDB itself and not shown to user). The table contains all projected attributes when creating the GSI. Whenever, a record gets updated in main table, then the GSI table is also updated with the same (though there is a small lag as its not a transaction leading to eventual consistency). So, if you query the GSI immediately after updating a record, it can happen sometimes that you get old/stale data.