0
0
DynamodbHow-ToBeginner · 4 min read

How to Query Using Secondary Index in DynamoDB

To query using a secondary index in DynamoDB, specify the IndexName parameter in your Query request along with the key condition. This lets you retrieve items based on the alternate key defined in the secondary index instead of the primary key.
📐

Syntax

The basic syntax to query a DynamoDB table using a secondary index includes specifying the IndexName parameter to target the index, and a KeyConditionExpression to filter items by the index's key attributes.

  • TableName: The name of your DynamoDB table.
  • IndexName: The name of the secondary index you want to query.
  • KeyConditionExpression: Expression to specify the key values to query.
  • ExpressionAttributeValues: Values used in the key condition expression.
  • ExpressionAttributeNames: Optional mapping for attribute names used in expressions.
javascript
const params = {
  TableName: 'YourTableName',
  IndexName: 'YourSecondaryIndexName',
  KeyConditionExpression: '#key = :value',
  ExpressionAttributeNames: {
    '#key': 'YourIndexPartitionKey'
  },
  ExpressionAttributeValues: {
    ':value': 'PartitionKeyValue'
  }
};

const result = await dynamodb.query(params).promise();
💻

Example

This example shows how to query a DynamoDB table named Orders using a secondary index called CustomerIndex. The index uses CustomerId as the partition key. The query retrieves all orders for a specific customer.

javascript
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();

async function queryBySecondaryIndex() {
  const params = {
    TableName: 'Orders',
    IndexName: 'CustomerIndex',
    KeyConditionExpression: 'CustomerId = :cid',
    ExpressionAttributeValues: {
      ':cid': 'C12345'
    }
  };

  try {
    const data = await dynamodb.query(params).promise();
    console.log('Query succeeded:', data.Items);
  } catch (err) {
    console.error('Query failed:', err);
  }
}

queryBySecondaryIndex();
Output
Query succeeded: [ { OrderId: 'O1001', CustomerId: 'C12345', Amount: 250 }, { OrderId: 'O1005', CustomerId: 'C12345', Amount: 450 } ]
⚠️

Common Pitfalls

Common mistakes when querying using a secondary index include:

  • Not specifying the IndexName, which causes the query to run on the primary key instead.
  • Using a KeyConditionExpression that does not match the index's key schema.
  • Confusing the partition key and sort key names of the index.
  • Expecting to query on non-key attributes without using a filter, which is inefficient.

Always check your index's key schema and use the correct attribute names in your query.

javascript
/* Wrong: Missing IndexName, queries primary key instead */
const wrongParams = {
  TableName: 'Orders',
  KeyConditionExpression: 'CustomerId = :cid',
  ExpressionAttributeValues: { ':cid': 'C12345' }
};

/* Right: Specify IndexName to query secondary index */
const rightParams = {
  TableName: 'Orders',
  IndexName: 'CustomerIndex',
  KeyConditionExpression: 'CustomerId = :cid',
  ExpressionAttributeValues: { ':cid': 'C12345' }
};
📊

Quick Reference

ParameterDescription
TableNameName of the DynamoDB table
IndexNameName of the secondary index to query
KeyConditionExpressionExpression to specify key values for the query
ExpressionAttributeValuesValues used in the key condition expression
ExpressionAttributeNamesOptional mapping for attribute names used in expressions

Key Takeaways

Always specify the IndexName parameter to query a secondary index in DynamoDB.
Use KeyConditionExpression with the index's key attributes to filter results.
Check your secondary index's key schema to write correct queries.
Queries without IndexName target the table's primary key, not the secondary index.
Avoid filtering on non-key attributes in the query; use filters after querying keys.