// Indexes give you access to alternate query patterns, and can speed up
queries.
Creating an Index
Indexes in DynamoDB are different from their relational counterparts. When you create a secondary index, you must specify its key attributes—a partition key and a sort key. After you create the secondary index, you can Query it or Scan it just as you would with a table.
Dynamo DB supports 2 kinds of Indices
- Global secondary indexes – The primary key of the index can be any two attributes from its table.
- Local secondary indexes – The partition key of the index must be the same as the partition key of its table. However, the sort key can be any other attribute.
Add a global secondary index to an existing table, using the UpdateTable action and specifying GlobalSecondaryIndexUpdatesFollowing. Following params are required
- IndexName: A name for the index.
- KeySchema: The attributes that are used for the index's primary key.
- Projection: Attributes from the table that are copied to the index.
- ProvisionedThroughput(for provisioned tables): number of reads and writes per second that you need for this index.
{
TableName: "Music",
AttributeDefinitions:[
{AttributeName: "Genre", AttributeType: "S"},
{AttributeName: "Price", AttributeType: "N"}
],
GlobalSecondaryIndexUpdates: [{
Create: {
IndexName: "GenreAndPriceIndex",
KeySchema: [
{AttributeName: "Genre", KeyType: "HASH"}, //Partition key
{AttributeName: "Price", KeyType: "RANGE"}, //Sort key
],
Projection: { "ProjectionType": "ALL" },
ProvisionedThroughput: { "ReadCapacityUnits": 1,"WriteCapacityUnits": 1 } // Only specified if using provisioned mode
} } ]
}
// DynamoDB does not have a query optimizer, so a secondary index is
only used when you Query it or Scan it.
// You can request strongly consistent Query or Scan actions on a
table or a local secondary index. However, global secondary indexes
support only eventual consistency.
Querying an Index
perform Query operations directly on the index, in the same way as on a table. must specify both TableName and IndexName
{
TableName: "Music",
IndexName: "GenreAndPriceIndex",
KeyConditionExpression: "Genre = :genre and Price < :price",
ExpressionAttributeValues: {
":genre": "Country",
":price": 0.50
}
};