0
0
DynamoDBquery~5 mins

Key condition expressions in DynamoDB

Choose your learning style9 modes available
Introduction

Key condition expressions help you find items in a DynamoDB table by specifying which keys to look for. They make searching fast and easy.

When you want to get all orders for a specific customer from an orders table.
When you need to find a user's profile using their unique user ID.
When you want to retrieve all events that happened on a certain date.
When you want to get items sorted by a range key, like dates or numbers.
When you want to filter data by primary key or sort key in a query.
Syntax
DynamoDB
partitionKeyName = :partitionKeyVal [AND sortKeyName operator :sortKeyVal]

The partition key condition is required and uses '='.

The sort key condition is optional and can use operators like =, <, <=, >, >=, BETWEEN, or begins_with.

Examples
Finds all items where the partition key 'UserId' equals a specific value.
DynamoDB
UserId = :userId
Finds items for a user where the sort key 'CreatedAt' is on or after a start date.
DynamoDB
UserId = :userId AND CreatedAt >= :startDate
Finds items for a user where 'CreatedAt' is between two dates.
DynamoDB
UserId = :userId AND CreatedAt BETWEEN :startDate AND :endDate
Finds items for a user where the sort key 'Title' starts with a given prefix.
DynamoDB
UserId = :userId AND begins_with(Title, :prefix)
Sample Program

This example shows how to write a key condition expression to get orders for a customer starting from a certain date.

DynamoDB
QueryInput = {
  TableName: "Orders",
  KeyConditionExpression: "CustomerId = :cid AND OrderDate >= :date",
  ExpressionAttributeValues: {
    ":cid": { S: "C123" },
    ":date": { S: "2023-01-01" }
  }
}

// This query finds all orders for customer 'C123' from January 1, 2023 onwards.
OutputSuccess
Important Notes

Always specify the partition key in your key condition expression.

Sort key conditions help narrow down results but are optional.

Use ExpressionAttributeValues to safely pass values and avoid injection.

Summary

Key condition expressions let you quickly find items by their keys.

Partition key condition is required; sort key condition is optional.

Use operators like =, BETWEEN, and begins_with for flexible queries.