Amazon DynamoDB: Create and Query a Global Secondary Index
See more Amazon DynamoDB Examples
Choose create, status, or query. Create adds DataIndex to the on-demand ExampleItems table: Data is its string partition key and SK its string sort key. The index includes Version in addition to automatically projected table/index keys. Creation/backfill is asynchronous and billable. Status checks DescribeTable once; repeat with a delay and deadline until the index is ACTIVE. Query checks readiness before sending paginated requests.
Items need correctly typed Data and SK attributes to appear in this index. Items missing an index key are omitted (a sparse index). Existing examples already write these attributes. GSI reads are eventually consistent, so recent writes may not appear immediately. GSI queries can retrieve only projected attributes. An index adds storage/write cost; provisioned-mode tables also require appropriate index throughput settings, which this on-demand example intentionally omits.
The item examples use the ExampleItems table from Create a Table, with string partition key PK and string sort key SK. Wait for ACTIVE. DynamoDB AttributeValue JSON uses wrappers such as {"S":"text"}, {"N":"123.45"}, and {"BOOL":true}. Numeric attributes travel as strings; preserve their precision rather than converting them to int or floating point. Names and IDs remain strings.
Uses DynamoDB's regional JSON API: POST to /, application/x-amz-json-1.0, and an operation-specific X-Amz-Target: DynamoDB_20120810... header. The 20120810 API identifier is still current. Chilkat.Rest and AuthAws sign each request with AWS Signature Version 4, service dynamodb. Set the region once; the example builds the matching commercial AWS endpoint. Other AWS partitions use their own endpoint suffixes.
Read current IAM credentials from a private qa_data/aws/dynamodb.json containing string fields access_key, secret_key, and, for temporary credentials, session_token. Prefer short-lived role credentials and refresh them before expiry. This code explicitly reads the file; it does not discover an AWS profile or refresh credentials automatically. The session token is included in the signed X-Amz-Security-Token query parameter, so keep request URLs and diagnostics private. A Socket explicitly enables TLS certificate verification and is supplied to Rest. Reuse the configured Rest object for subsequent requests.
IAM permissions for the illustrated actions: dynamodb:UpdateTable, dynamodb:DescribeTable, dynamodb:Query. Limit access to the appropriate table, index, backup, and restore-target resources. Restoring customer-managed-key encrypted data can also require KMS permissions.
Checks transport completion, HTTP 200, and JSON validity separately. DynamoDB errors include __type and message. HTTP 400 can mean throttling, failed conditions, invalid input, or expired credentials. Use bounded exponential backoff with jitter for retryable failures; renew expired credentials. A failed condition requires an application decision, not an automatic retry. For writes with an uncertain outcome, read/reconcile before retrying. Only the explicitly described batch retries are automatic; other writes are not automatically replayed.
UpdateTable reference, DescribeTable reference, Query reference
Chilkat DataFlex Downloads
Use ChilkatAx-win32.pkg
Procedure Test
Boolean iSuccess
Handle hoCredentials
String sRegion
Handle hoEndpoint
Variant vAws
Handle hoAws
Handle hoRest
Variant vConnection
Handle hoConnection
Handle hoBody
Handle hoResult
Variant vRequestBody
Handle hoRequestBody
Variant vResponseBody
Handle hoResponseBody
Handle hoErrorType
String sTableName
String sAction
String sIndexStatus
Integer iIndexPosition
Variant vLastKey
Handle hoLastKey
Variant vStartKey
Handle hoStartKey
Handle hoSeenKeys
Boolean iMore
Integer iPage
Integer i
String sKeyText
String sTemp1
String sTemp2
Integer iTemp1
Boolean bTemp1
Move False To iSuccess
// Assumes Chilkat is unlocked. See Global Unlock Sample.
Move False To iSuccess
// Private configuration, not a file in public web content or source control.
// Load current IAM credentials authorized for the DynamoDB operation.
Get Create (RefClass(cComChilkatJsonObject)) To hoCredentials
If (Not(IsComObjectCreated(hoCredentials))) Begin
Send CreateComObject of hoCredentials
End
Set ComStrict Of hoCredentials To True
Get ComLoadFile Of hoCredentials "qa_data/aws/dynamodb.json" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not load private AWS credentials."
Procedure_Return
End
Get ComJsonTypeOf Of hoCredentials "access_key" To iTemp1
Get ComStringOf Of hoCredentials "access_key" To sTemp1
If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
Showln "Missing or invalid access_key."
Procedure_Return
End
Get ComJsonTypeOf Of hoCredentials "secret_key" To iTemp1
Get ComStringOf Of hoCredentials "secret_key" To sTemp1
If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
Showln "Missing or invalid secret_key."
Procedure_Return
End
// Set this once to the region containing the table.
Move "us-west-2" To sRegion
Get Create (RefClass(cComChilkatStringBuilder)) To hoEndpoint
If (Not(IsComObjectCreated(hoEndpoint))) Begin
Send CreateComObject of hoEndpoint
End
Get ComAppend Of hoEndpoint "dynamodb." To iSuccess
Get ComAppend Of hoEndpoint sRegion To iSuccess
Get ComAppend Of hoEndpoint ".amazonaws.com" To iSuccess
Get Create (RefClass(cComChilkatAuthAws)) To hoAws
If (Not(IsComObjectCreated(hoAws))) Begin
Send CreateComObject of hoAws
End
Get ComStringOf Of hoCredentials "access_key" To sTemp1
Set ComAccessKey Of hoAws To sTemp1
Get ComStringOf Of hoCredentials "secret_key" To sTemp1
Set ComSecretKey Of hoAws To sTemp1
Set ComRegion Of hoAws To sRegion
Set ComServiceName Of hoAws To "dynamodb"
Set ComSignatureVersion Of hoAws To 4
Get Create (RefClass(cComChilkatRest)) To hoRest
If (Not(IsComObjectCreated(hoRest))) Begin
Send CreateComObject of hoRest
End
Set ComConnectTimeoutMs Of hoRest To 20000
Set ComIdleTimeoutMs Of hoRest To 60000
Get pvComObject of hoAws to vAws
Get ComSetAuthAws Of hoRest vAws To iSuccess
If (iSuccess <> True) Begin
Showln "Could not configure AWS signing."
Procedure_Return
End
// Temporary IAM/STS credentials require their session token on every signed request.
// AddQueryParam includes it in SigV4's canonical query. Never log the request URL.
// Leave session_token absent or empty only for credentials that do not have one.
Get ComHasMember Of hoCredentials "session_token" To bTemp1
If (bTemp1 = True) Begin
Get ComJsonTypeOf Of hoCredentials "session_token" To iTemp1
If (iTemp1 <> 1) Begin
Showln "session_token must be a string."
Procedure_Return
End
Get ComStringOf Of hoCredentials "session_token" To sTemp1
If (sTemp1 <> "") Begin
Get ComStringOf Of hoCredentials "session_token" To sTemp1
Get ComAddQueryParam Of hoRest "X-Amz-Security-Token" sTemp1 To iSuccess
If (iSuccess <> True) Begin
Showln "Could not set the session-token parameter."
Procedure_Return
End
End
End
// Supply a Socket to explicitly enable TLS certificate verification.
Get Create (RefClass(cComChilkatSocket)) To hoConnection
If (Not(IsComObjectCreated(hoConnection))) Begin
Send CreateComObject of hoConnection
End
Set ComRequireSslCertVerify Of hoConnection To True
Set ComMaxReadIdleMs Of hoConnection To 60000
Set ComMaxSendIdleMs Of hoConnection To 60000
Get ComGetAsString Of hoEndpoint To sTemp1
Get ComConnect Of hoConnection sTemp1 443 True 20000 To iSuccess
If (iSuccess <> True) Begin
Showln "TLS connection failed; inspect diagnostics privately."
Procedure_Return
End
Get pvComObject of hoConnection to vConnection
Get ComUseConnection Of hoRest vConnection True To iSuccess
If (iSuccess <> True) Begin
Showln "Could not attach the TLS connection."
Procedure_Return
End
Get ComAddHeader Of hoRest "Content-Type" "application/x-amz-json-1.0" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not set the content type."
Procedure_Return
End
Get Create (RefClass(cComChilkatJsonObject)) To hoBody
If (Not(IsComObjectCreated(hoBody))) Begin
Send CreateComObject of hoBody
End
Get Create (RefClass(cComChilkatJsonObject)) To hoResult
If (Not(IsComObjectCreated(hoResult))) Begin
Send CreateComObject of hoResult
End
Set ComStrict Of hoResult To True
Get Create (RefClass(cComChilkatStringBuilder)) To hoRequestBody
If (Not(IsComObjectCreated(hoRequestBody))) Begin
Send CreateComObject of hoRequestBody
End
Get Create (RefClass(cComChilkatStringBuilder)) To hoResponseBody
If (Not(IsComObjectCreated(hoResponseBody))) Begin
Send CreateComObject of hoResponseBody
End
Get Create (RefClass(cComChilkatStringBuilder)) To hoErrorType
If (Not(IsComObjectCreated(hoErrorType))) Begin
Send CreateComObject of hoErrorType
End
Move "ExampleItems" To sTableName
// Choose "create", "status", or "query". Start with status on an existing table.
Move "status" To sAction
If ((sAction <> "create") And (sAction <> "status") And (sAction <> "query")) Begin
Showln "Choose create, status, or query."
Procedure_Return
End
If (sAction = "create") Begin
Get ComAddHeader Of hoRest "X-Amz-Target" "DynamoDB_20120810.UpdateTable" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not set the DynamoDB operation."
Procedure_Return
End
Get ComUpdateString Of hoBody "TableName" sTableName To iSuccess
Get ComUpdateString Of hoBody "AttributeDefinitions[0].AttributeName" "Data" To iSuccess
Get ComUpdateString Of hoBody "AttributeDefinitions[0].AttributeType" "S" To iSuccess
Get ComUpdateString Of hoBody "AttributeDefinitions[1].AttributeName" "SK" To iSuccess
Get ComUpdateString Of hoBody "AttributeDefinitions[1].AttributeType" "S" To iSuccess
Get ComUpdateString Of hoBody "GlobalSecondaryIndexUpdates[0].Create.IndexName" "DataIndex" To iSuccess
Get ComUpdateString Of hoBody "GlobalSecondaryIndexUpdates[0].Create.KeySchema[0].AttributeName" "Data" To iSuccess
Get ComUpdateString Of hoBody "GlobalSecondaryIndexUpdates[0].Create.KeySchema[0].KeyType" "HASH" To iSuccess
Get ComUpdateString Of hoBody "GlobalSecondaryIndexUpdates[0].Create.KeySchema[1].AttributeName" "SK" To iSuccess
Get ComUpdateString Of hoBody "GlobalSecondaryIndexUpdates[0].Create.KeySchema[1].KeyType" "RANGE" To iSuccess
Get ComUpdateString Of hoBody "GlobalSecondaryIndexUpdates[0].Create.Projection.ProjectionType" "INCLUDE" To iSuccess
Get ComUpdateString Of hoBody "GlobalSecondaryIndexUpdates[0].Create.Projection.NonKeyAttributes[0]" "Version" To iSuccess
// EmitSb appends. Clear the request buffer before each request/page.
Send ComClear To hoRequestBody
Get pvComObject of hoRequestBody to vRequestBody
Get ComEmitSb Of hoBody vRequestBody To iSuccess
If (iSuccess <> True) Begin
Showln "Could not encode the request."
Procedure_Return
End
Get pvComObject of hoRequestBody to vRequestBody
Get pvComObject of hoResponseBody to vResponseBody
Get ComFullRequestSb Of hoRest "POST" "/" vRequestBody vResponseBody To iSuccess
If (iSuccess <> True) Begin
Showln "Request did not complete; inspect diagnostics privately."
// A write may already have succeeded. Reconcile its outcome before retrying.
Procedure_Return
End
Get ComResponseStatusCode Of hoRest To iTemp1
If (iTemp1 <> 200) Begin
Get ComResponseStatusCode Of hoRest To iTemp1
Showln "DynamoDB HTTP status: " iTemp1
Get pvComObject of hoResponseBody to vResponseBody
Get ComLoadSb Of hoResult vResponseBody To iSuccess
If (iSuccess = True) Begin
Get ComJsonTypeOf Of hoResult "__type" To iTemp1
If (iTemp1 = 1) Begin
Send ComClear To hoErrorType
Get ComStringOf Of hoResult "__type" To sTemp1
Get ComAppend Of hoErrorType sTemp1 To iSuccess
Get ComGetAsString Of hoErrorType To sTemp1
Showln "AWS error type: " sTemp1
End
End
// Throttling can be HTTP 400. Inspect __type, not just the HTTP status.
// Keep full error messages, item data, and signed request diagnostics private.
Procedure_Return
End
Get pvComObject of hoResponseBody to vResponseBody
Get ComLoadSb Of hoResult vResponseBody To iSuccess
If (iSuccess <> True) Begin
Showln "Expected a well-formed JSON response."
Procedure_Return
End
Get ComJsonTypeOf Of hoResult "TableDescription.TableStatus" To iTemp1
Get ComStringOf Of hoResult "TableDescription.TableStatus" To sTemp1
If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
Showln "Missing or invalid TableDescription.TableStatus."
Procedure_Return
End
Showln "Index creation accepted. Run status until DataIndex is ACTIVE."
Procedure_Return
End
Get ComAddHeader Of hoRest "X-Amz-Target" "DynamoDB_20120810.DescribeTable" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not set the DynamoDB operation."
Procedure_Return
End
Get ComUpdateString Of hoBody "TableName" sTableName To iSuccess
// EmitSb appends. Clear the request buffer before each request/page.
Send ComClear To hoRequestBody
Get pvComObject of hoRequestBody to vRequestBody
Get ComEmitSb Of hoBody vRequestBody To iSuccess
If (iSuccess <> True) Begin
Showln "Could not encode the request."
Procedure_Return
End
Get pvComObject of hoRequestBody to vRequestBody
Get pvComObject of hoResponseBody to vResponseBody
Get ComFullRequestSb Of hoRest "POST" "/" vRequestBody vResponseBody To iSuccess
If (iSuccess <> True) Begin
Showln "Request did not complete; inspect diagnostics privately."
// A write may already have succeeded. Reconcile its outcome before retrying.
Procedure_Return
End
Get ComResponseStatusCode Of hoRest To iTemp1
If (iTemp1 <> 200) Begin
Get ComResponseStatusCode Of hoRest To iTemp1
Showln "DynamoDB HTTP status: " iTemp1
Get pvComObject of hoResponseBody to vResponseBody
Get ComLoadSb Of hoResult vResponseBody To iSuccess
If (iSuccess = True) Begin
Get ComJsonTypeOf Of hoResult "__type" To iTemp1
If (iTemp1 = 1) Begin
Send ComClear To hoErrorType
Get ComStringOf Of hoResult "__type" To sTemp1
Get ComAppend Of hoErrorType sTemp1 To iSuccess
Get ComGetAsString Of hoErrorType To sTemp1
Showln "AWS error type: " sTemp1
End
End
// Throttling can be HTTP 400. Inspect __type, not just the HTTP status.
// Keep full error messages, item data, and signed request diagnostics private.
Procedure_Return
End
Get pvComObject of hoResponseBody to vResponseBody
Get ComLoadSb Of hoResult vResponseBody To iSuccess
If (iSuccess <> True) Begin
Showln "Expected a well-formed JSON response."
Procedure_Return
End
Get ComJsonTypeOf Of hoResult "Table.TableStatus" To iTemp1
Get ComStringOf Of hoResult "Table.TableStatus" To sTemp1
If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
Showln "Missing or invalid Table.TableStatus."
Procedure_Return
End
Move "" To sIndexStatus
Move 0 To iIndexPosition
While (iIndexPosition < (ComSizeOfArray(hoResult, "Table.GlobalSecondaryIndexes")))
Set ComI Of hoResult To iIndexPosition
Get ComStringOf Of hoResult "Table.GlobalSecondaryIndexes[i].IndexName" To sTemp1
If (sTemp1 = "DataIndex") Begin
Get ComStringOf Of hoResult "Table.GlobalSecondaryIndexes[i].IndexStatus" To sIndexStatus
End
Move (iIndexPosition + 1) To iIndexPosition
Loop
Showln "DataIndex status (empty means absent): " sIndexStatus
If (sAction = "status") Begin
Procedure_Return
End
If (sIndexStatus <> "ACTIVE") Begin
Showln "The index is not ACTIVE; no query sent."
Procedure_Return
End
Send ComClear To hoBody
Get ComAddHeader Of hoRest "X-Amz-Target" "DynamoDB_20120810.Query" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not set the DynamoDB operation."
Procedure_Return
End
Get ComUpdateString Of hoBody "TableName" sTableName To iSuccess
Get ComUpdateString Of hoBody "IndexName" "DataIndex" To iSuccess
Get ComUpdateString Of hoBody "KeyConditionExpression" "#data = :value" To iSuccess
Get ComUpdateString Of hoBody "ExpressionAttributeNames.#data" "Data" To iSuccess
Get ComUpdateString Of hoBody "ExpressionAttributeValues.:value.S" "Initial value" To iSuccess
Get ComUpdateBool Of hoBody "ConsistentRead" False To iSuccess
Get ComUpdateInt Of hoBody "Limit" 100 To iSuccess
Get ComUpdateString Of hoBody "ReturnConsumedCapacity" "INDEXES" To iSuccess
Get Create (RefClass(cComChilkatJsonObject)) To hoLastKey
If (Not(IsComObjectCreated(hoLastKey))) Begin
Send CreateComObject of hoLastKey
End
Get Create (RefClass(cComChilkatJsonObject)) To hoStartKey
If (Not(IsComObjectCreated(hoStartKey))) Begin
Send CreateComObject of hoStartKey
End
Get Create (RefClass(cComChilkatHashtable)) To hoSeenKeys
If (Not(IsComObjectCreated(hoSeenKeys))) Begin
Send CreateComObject of hoSeenKeys
End
Move True To iMore
Move 0 To iPage
While (iMore = True)
If (iPage = 1000) Begin
Showln "Stopped at 1000 pages; index query is incomplete. Save ExclusiveStartKey to resume."
Procedure_Return
End
// EmitSb appends. Clear the request buffer before each request/page.
Send ComClear To hoRequestBody
Get pvComObject of hoRequestBody to vRequestBody
Get ComEmitSb Of hoBody vRequestBody To iSuccess
If (iSuccess <> True) Begin
Showln "Could not encode the request."
Procedure_Return
End
Get pvComObject of hoRequestBody to vRequestBody
Get pvComObject of hoResponseBody to vResponseBody
Get ComFullRequestSb Of hoRest "POST" "/" vRequestBody vResponseBody To iSuccess
If (iSuccess <> True) Begin
Showln "Request did not complete; inspect diagnostics privately."
// A write may already have succeeded. Reconcile its outcome before retrying.
Procedure_Return
End
Get ComResponseStatusCode Of hoRest To iTemp1
If (iTemp1 <> 200) Begin
Get ComResponseStatusCode Of hoRest To iTemp1
Showln "DynamoDB HTTP status: " iTemp1
Get pvComObject of hoResponseBody to vResponseBody
Get ComLoadSb Of hoResult vResponseBody To iSuccess
If (iSuccess = True) Begin
Get ComJsonTypeOf Of hoResult "__type" To iTemp1
If (iTemp1 = 1) Begin
Send ComClear To hoErrorType
Get ComStringOf Of hoResult "__type" To sTemp1
Get ComAppend Of hoErrorType sTemp1 To iSuccess
Get ComGetAsString Of hoErrorType To sTemp1
Showln "AWS error type: " sTemp1
End
End
// Throttling can be HTTP 400. Inspect __type, not just the HTTP status.
// Keep full error messages, item data, and signed request diagnostics private.
Procedure_Return
End
Get pvComObject of hoResponseBody to vResponseBody
Get ComLoadSb Of hoResult vResponseBody To iSuccess
If (iSuccess <> True) Begin
Showln "Expected a well-formed JSON response."
Procedure_Return
End
Get ComJsonTypeOf Of hoResult "Items" To iTemp1
If (iTemp1 <> 4) Begin
Showln "Expected Items array."
Procedure_Return
End
Move 0 To i
While (i < (ComSizeOfArray(hoResult, "Items")))
Set ComI Of hoResult To i
Get ComJsonTypeOf Of hoResult "Items[i].PK.S" To iTemp1
Get ComStringOf Of hoResult "Items[i].PK.S" To sTemp1
If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
Showln "Missing or invalid Items[i].PK.S."
Procedure_Return
End
Get ComJsonTypeOf Of hoResult "Items[i].SK.S" To iTemp1
Get ComStringOf Of hoResult "Items[i].SK.S" To sTemp1
If ((iTemp1 <> 1) Or (sTemp1 = "")) Begin
Showln "Missing or invalid Items[i].SK.S."
Procedure_Return
End
Get ComStringOf Of hoResult "Items[i].PK.S" To sTemp1
Get ComStringOf Of hoResult "Items[i].SK.S" To sTemp2
Showln "PK: " sTemp1 "; SK: " sTemp2
Move (i + 1) To i
Loop
Get ComSizeOfArray Of hoResult "Items" To iTemp1
Showln "Items returned in this page: " iTemp1
Get ComHasMember Of hoResult "ConsumedCapacity.CapacityUnits" To bTemp1
If (bTemp1 = True) Begin
// Capacity can be fractional; do not truncate it with IntOf.
Get ComStringOf Of hoResult "ConsumedCapacity.CapacityUnits" To sTemp1
Showln "Consumed capacity: " sTemp1
End
Move (iPage + 1) To iPage
Move False To iMore
// Empty Items does not imply completion; filtering can remove an entire page.
Get ComHasMember Of hoResult "LastEvaluatedKey" To bTemp1
If (bTemp1 = True) Begin
Get ComJsonTypeOf Of hoResult "LastEvaluatedKey" To iTemp1
If (iTemp1 <> 3) Begin
Showln "Expected LastEvaluatedKey object."
Procedure_Return
End
Get pvComObject of hoLastKey to vLastKey
Get ComObjectOf2 Of hoResult "LastEvaluatedKey" vLastKey To iSuccess
If (iSuccess <> True) Begin
Showln "Could not read the continuation key."
Procedure_Return
End
Get ComSize Of hoLastKey To iTemp1
If (iTemp1 > 0) Begin
// Preserve the entire typed key map. Sort members only to detect repeated keys,
// even if a response changes JSON member order.
Send ComSort To hoLastKey True True
Set ComEmitCompact Of hoLastKey To True
Get ComEmit Of hoLastKey To sKeyText
Get ComContains Of hoSeenKeys sKeyText To bTemp1
If (bTemp1 = True) Begin
Showln "Repeated query key; index query is incomplete."
Procedure_Return
End
Get ComAddInt Of hoSeenKeys sKeyText 1 To iSuccess
If (iSuccess <> True) Begin
Showln "Could not track query pages."
Procedure_Return
End
Get ComUpdateNewObject Of hoBody "ExclusiveStartKey" To iSuccess
If (iSuccess <> True) Begin
Showln "Could not prepare ExclusiveStartKey."
Procedure_Return
End
Get pvComObject of hoStartKey to vStartKey
Get ComObjectOf2 Of hoBody "ExclusiveStartKey" vStartKey To iSuccess
If (iSuccess <> True) Begin
Showln "Could not access ExclusiveStartKey."
Procedure_Return
End
Get ComLoad Of hoStartKey sKeyText To iSuccess
If (iSuccess <> True) Begin
Showln "Could not copy the full continuation key."
Procedure_Return
End
Move True To iMore
End
End
Loop
Showln "Index query complete."
End_Procedure