AWS Developer Tools Blog
Create, Update, and Delete Global Secondary Indexes Using the HAQM DynamoDB Document API
HAQM DynamoDB recently announced a new feature, online indexing that helps you create and modify global secondary indexes (GSI) after table creation. You can also delete a global secondary index associated with a table at any time. This blog post shows how easy it is to use the HAQM DynamoDB Document API of AWS SDK for Java to perform these operations.
Let’s say your application has a Customer table with CustomerId as the primary key and holds the personal details of a customer.
{ "CustomerId" : 1000, "FirstName" : "John", "LastName" : "Myers", "Gender" : "M", "AddressLine1" : "156th Avenue", "City" : "Redmond", "State" : "WA", "Zip" : "98052" }
You want to create a new global secondary index on the State
attribute that helps you in search operations. You can do this with the following code:
// Initialize the DynamoDB object.
DynamoDB dynamo = new DynamoDB(Regions.US_EAST_1);
// Retrieve the reference to an existing HAQM DynamoDB table.
Table table = dynamo.getTable("Customer");
// Create a new Global Secondary Index.
Index index = table.createGSI(
new CreateGlobalSecondaryIndexAction()
.withIndexName("state-index")
.withKeySchema(
new KeySchemaElement("State", KeyType.HASH))
.withProvisionedThroughput(
new ProvisionedThroughput(25L, 25L))
.withProjection(
new Projection()
.withProjectionType(ProjectionType.ALL)),
new AttributeDefinition("State",
ScalarAttributeType.S));
// Wait until the index is active.
index.waitForActive();
HAQM DynamoDB allows you to modify the provisioned throughput
of a global secondary index at any time after index creation. You can do this with the following code:
// Update the provisioned throughput of the Global Secondary Index.
index.updateGSI(new ProvisionedThroughput(5L, 5L));
// Wait until the index is active.
index.waitForActive();
You can also delete a global secondary index using the following code:
// Delete the Global Secondary Index.
index.deleteGSI();
// Wait until the index is deleted.
index.waitForDelete();
Do you use the HAQM DynamoDB Document API to access HAQM DynamoDB? Let us know what you think!