A Quick Guide to DynamoDB Secondary Indexes

When you create tables in DynamoDB, you must specify primary key attributes. These primary key attributes can then be used to retrieve data from your tables.

To more efficiently find your data, DynamoDB creates indexes for those attributes. Sometimes, however, you may need to query data using an attribute that’s not in one of your primary keys. This is where secondary indexes can help.

DynamoDB Table to illustrate primary keys (partition keys and sort keys) and secondary indexes
DynamoDB and primary keys (partition keys and sort keys) and secondary indexes

In the example above, we have a Reply table for our forums. The Id is our partition key, ReplyDateTime our sort key, and these two attributes make up our primary key. This primary key can be used to query data.

Say we want all of the Amazon DynamoDB#DynamoDB Thread 2 threads. We can query for that, and DynamoDB, in turn, gives us 3 items that match this query. Since we have ReplyDateTime as a sort key, we could also ask for replies after a specified date.

But what if we wanted to query by users who posted replies? We can’t use the PostedBy attribute to pull up all of User A’s messages because it is not a key attribute.

This is where secondary indexes come into play. Depending on the secondary index that we use, we could set PostedBy as another sort key (in addition to the ReplyDateTime sort key) or even set PostedBy as a partition key! Both of these options give us the ability to filter messages by user. (more…)