0
0
DynamodbHow-ToBeginner · 4 min read

How to Use KeyConditionExpression in DynamoDB Queries

Use KeyConditionExpression in DynamoDB queries to specify the conditions for the partition key and optionally the sort key. It filters items by matching the primary key attributes, enabling efficient retrieval of data. You provide the expression as a string with placeholders and supply values via ExpressionAttributeValues.
📐

Syntax

The KeyConditionExpression defines the key values to query in a DynamoDB table. It must include the partition key equality condition and can include sort key conditions using operators like =, >, <, BETWEEN, or begins_with().

Use placeholders for values in the expression and provide actual values in ExpressionAttributeValues.

json
KeyConditionExpression: "PartitionKeyName = :partitionKeyVal AND SortKeyName BETWEEN :startVal AND :endVal",
ExpressionAttributeValues: {
  ":partitionKeyVal": { S: "ExamplePartitionKey" },
  ":startVal": { N: "100" },
  ":endVal": { N: "200" }
}
💻

Example

This example shows how to query a DynamoDB table named Orders to get all orders for a customer with ID 12345 where the order date is between two dates.

javascript
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");

const client = new DynamoDBClient({ region: "us-east-1" });

async function queryOrders() {
  const params = {
    TableName: "Orders",
    KeyConditionExpression: "CustomerId = :custId AND OrderDate BETWEEN :startDate AND :endDate",
    ExpressionAttributeValues: {
      ":custId": { S: "12345" },
      ":startDate": { S: "2023-01-01" },
      ":endDate": { S: "2023-12-31" }
    }
  };

  try {
    const data = await client.send(new QueryCommand(params));
    console.log("Query succeeded:", data.Items);
  } catch (err) {
    console.error("Query failed:", err);
  }
}

queryOrders();
Output
Query succeeded: [ { CustomerId: { S: '12345' }, OrderDate: { S: '2023-06-15' }, OrderId: { S: 'A001' }, Amount: { N: '250' } }, { CustomerId: { S: '12345' }, OrderDate: { S: '2023-09-10' }, OrderId: { S: 'A002' }, Amount: { N: '150' } } ]
⚠️

Common Pitfalls

  • Missing partition key condition: The KeyConditionExpression must always include the partition key with an equality operator.
  • Using non-key attributes: You cannot filter by non-key attributes in KeyConditionExpression; use FilterExpression for that.
  • Incorrect placeholders: Placeholders in the expression must match keys in ExpressionAttributeValues.
json
/* Wrong: Missing partition key condition */
KeyConditionExpression: "OrderDate = :date",
ExpressionAttributeValues: {
  ":date": { S: "2023-06-15" }
}

/* Right: Include partition key */
KeyConditionExpression: "CustomerId = :custId AND OrderDate = :date",
ExpressionAttributeValues: {
  ":custId": { S: "12345" },
  ":date": { S: "2023-06-15" }
}
📊

Quick Reference

PartDescriptionExample
Partition KeyMust be compared with '=' operatorCustomerId = :custId
Sort KeyOptional; supports '=', '<', '>', 'BETWEEN', 'begins_with()'OrderDate BETWEEN :start AND :end
PlaceholdersUse in expression and define in ExpressionAttributeValues:custId, :start, :end
ExpressionAttributeValuesMap placeholders to actual values{ ":custId": { S: "123" } }

Key Takeaways

Always include the partition key with '=' in KeyConditionExpression.
Use placeholders and ExpressionAttributeValues to safely pass values.
Sort key conditions are optional but must use supported operators.
KeyConditionExpression filters by key attributes only, not other columns.
Common errors include missing partition key or mismatched placeholders.