Introduction to Secondary Indexes In DynamoDB
Understand the basics of the local secondary indexes and global secondary indexes.
Utility of secondary indexes
We have seen how we can query on primary keys or scan the table. Both the options for reading data have their respective trade-offs. Querying on the primary key is fast, but it can only give us a limited set of access patterns. The scan can give us any access pattern, but it is slow and costly. There is a third way, using a secondary index, which is relatively cheap and provides us with more access patterns.
Reading option | Access patterns | Cost | Speed |
---|---|---|---|
Query on primary key | Limited | Low | High |
Scan on table | Many (virtually all) | Very high | Slow |
Query on secondary indexes | Moderate | Moderate | High |
Types of secondary indexes
There are two types of secondary indexes:
-
Global Secondary Index(GSI): This index allows us to define an alternate partition key and an optional sort key. This function is similar to that of creating a copy of the table with a new primary key.
-
Local Secondary Index(LSI): This index allows us to define a new sort key with the same partition key. This function is similar to that of keeping a new copy of each partition of our table.
Alternate partition key | Alternate sort key | |
---|---|---|
Global secondary index | Yes | Optionally |
Local secondary index | No | Yes |
Considerations while choosing secondary indexes
Secondary indexes are powerful but they come with their own set of responsibilities.
- Secondary indexes increase your read and write costs.
- We can only create local secondary indexes at the time of creating the tables.
- LSIs use the same partition key as the table and consume read and write capacity units from the table’s provisioned units.
- GSIs can have their own separate partition keys. We also need to provision throughput units for GSI separately. We can create or delete GSI for an existing table.
Get hands-on with 1400+ tech skills courses.