DynamoDB allows you to create secondary indexes to account for additional data access patterns on your table. Secondary indexes are a powerful way to add query flexibility to a DynamoDB table.
DynamoDB has two kinds of secondary indexes: global secondary indexes and local secondary indexes. In this section, you add a global secondary index to your Category attribute that will allow you to retrieve all books in a particular category.
The following example script adds a global secondary index to an existing table.
import boto3
# Boto3 is the AWS SDK library for Python.
# You can use the low-level client to make API calls to DynamoDB.
client = boto3.client('dynamodb', region_name='us-east-1')
try:
resp = client.update_table(
TableName="Books",
# Any attributes used in your new global secondary index must be declared in AttributeDefinitions
AttributeDefinitions=[
{
"AttributeName": "Category",
"AttributeType": "S"
},
],
# This is where you add, update, or delete any global secondary indexes on your table.
GlobalSecondaryIndexUpdates=[
{
"Create": {
# You need to name your index and specifically refer to it when using it for queries.
"IndexName": "CategoryIndex",
# Like the table itself, you need to specify the key schema for an index.
# For a global secondary index, you can use a simple or composite key schema.
"KeySchema": [
{
"AttributeName": "Category",
"KeyType": "HASH"
}
],
# You can choose to copy only specific attributes from the original item into the index.
# You might want to copy only a few attributes to save space.
"Projection": {
"ProjectionType": "ALL"
},
# Global secondary indexes have read and write capacity separate from the underlying table.
"ProvisionedThroughput": {
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1,
}
}
}
],
)
print("Secondary index added!")
except Exception as e:
print("Error updating table:")
print(e)
Creating a global secondary index has a lot in common with creating a table. You specify a name for the index, the attributes that will be in the index, the key schema of the index, and the provisioned throughput (the maximum capacity an application can consume from a table or index). Provisioned throughput on each index is separate from the provisioned throughput on a table. This allows you to define throughput granularly to meet your application’s needs.
Run the following command in your terminal to add your global secondary index.
$ python add_secondary_index.py
This script adds a global secondary index called CategoryIndex to your Books table.