A Global Secondary Index (GSI) lets you search your DynamoDB table using different keys than the main one. It helps you find data faster in new ways.
Creating GSI in DynamoDB
CreateTable {
TableName: string,
KeySchema: [
{ AttributeName: string, KeyType: 'HASH' | 'RANGE' }
],
AttributeDefinitions: [
{ AttributeName: string, AttributeType: 'S' | 'N' | 'B' }
],
GlobalSecondaryIndexes: [
{
IndexName: string,
KeySchema: [
{ AttributeName: string, KeyType: 'HASH' | 'RANGE' }
],
Projection: {
ProjectionType: 'ALL' | 'KEYS_ONLY' | 'INCLUDE',
NonKeyAttributes?: [string]
},
ProvisionedThroughput: {
ReadCapacityUnits: number,
WriteCapacityUnits: number
}
}
],
ProvisionedThroughput: {
ReadCapacityUnits: number,
WriteCapacityUnits: number
}
}The GlobalSecondaryIndexes section defines one or more GSIs.
Each GSI needs its own IndexName, KeySchema, and Projection to specify what data it holds.
GlobalSecondaryIndexes: [
{
IndexName: 'GSI1',
KeySchema: [
{ AttributeName: 'Category', KeyType: 'HASH' }
],
Projection: { ProjectionType: 'ALL' },
ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5 }
}
]GlobalSecondaryIndexes: [
{
IndexName: 'GSI2',
KeySchema: [
{ AttributeName: 'Status', KeyType: 'HASH' },
{ AttributeName: 'CreatedDate', KeyType: 'RANGE' }
],
Projection: { ProjectionType: 'INCLUDE', NonKeyAttributes: ['Description', 'Priority'] },
ProvisionedThroughput: { ReadCapacityUnits: 10, WriteCapacityUnits: 5 }
}
]This command creates a DynamoDB table named 'Products' with a primary key 'ProductId'. It also creates a GSI called 'CategoryIndex' that lets you query products by their 'Category'.
aws dynamodb create-table \
--table-name Products \
--attribute-definitions \
AttributeName=ProductId,AttributeType=S \
AttributeName=Category,AttributeType=S \
--key-schema AttributeName=ProductId,KeyType=HASH \
--provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
--global-secondary-indexes \
'[{
"IndexName": "CategoryIndex",
"KeySchema": [{"AttributeName":"Category","KeyType":"HASH"}],
"Projection": {"ProjectionType":"ALL"},
"ProvisionedThroughput": {"ReadCapacityUnits":5,"WriteCapacityUnits":5}
}]'GSIs let you query your data in new ways without changing your main table keys.
Remember to define the attributes used in your GSI in AttributeDefinitions.
Provisioned throughput for GSIs is separate from the main table and affects cost.
GSIs let you search your DynamoDB table using different keys.
They require defining new key schemas and projections.
Use GSIs to add flexible query options without rebuilding your table.