0
0
DynamoDBquery~5 mins

Query with sort key conditions in DynamoDB

Choose your learning style9 modes available
Introduction
You use sort key conditions to find specific items in a group, making your search faster and more focused.
When you want to find all orders made by a customer after a certain date.
When you need to get messages in a chat sorted by time.
When you want to list products in a category within a price range.
When you want to retrieve events that happened before a specific time.
When you want to get all versions of a document sorted by version number.
Syntax
DynamoDB
Query {
  KeyConditionExpression: "PartitionKeyName = :pkval AND SortKeyName operator :skval",
  ExpressionAttributeValues: {
    ":pkval": {S: "partition_key_value"},
    ":skval": {S: "sort_key_value"} // or {N: "sort_key_value"}
  }
}
The partition key must always be specified with '=' in the KeyConditionExpression.
The sort key condition can use operators like =, <, <=, >, >=, BETWEEN, or BEGINS_WITH.
Examples
Finds all items for user 'user123' created after January 1, 2023.
DynamoDB
KeyConditionExpression: "UserId = :uid AND CreatedAt > :date"
ExpressionAttributeValues: {
  ":uid": {S: "user123"},
  ":date": {S: "2023-01-01T00:00:00Z"}
}
Finds all books priced between 10 and 50.
DynamoDB
KeyConditionExpression: "Category = :cat AND Price BETWEEN :min AND :max"
ExpressionAttributeValues: {
  ":cat": {S: "Books"},
  ":min": {N: "10"},
  ":max": {N: "50"}
}
Finds all messages in chat 'chat789' where message IDs start with 'msg2023'.
DynamoDB
KeyConditionExpression: "ChatId = :cid AND begins_with(MessageId, :prefix)"
ExpressionAttributeValues: {
  ":cid": {S: "chat789"},
  ":prefix": {S: "msg2023"}
}
Sample Program
This query finds all orders for customer 'cust123' made on or after January 1, 2023.
DynamoDB
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();

const params = {
  TableName: 'Orders',
  KeyConditionExpression: 'CustomerId = :cid AND OrderDate >= :startDate',
  ExpressionAttributeValues: {
    ':cid': 'cust123',
    ':startDate': '2023-01-01'
  }
};

dynamodb.query(params, (err, data) => {
  if (err) {
    console.error('Error querying:', err);
  } else {
    console.log('Orders:', data.Items);
  }
});
OutputSuccess
Important Notes
You must always specify the partition key with '=' in the KeyConditionExpression.
Sort key conditions help narrow down results within the partition key.
Using BETWEEN or begins_with can help find ranges or prefixes in sort keys.
Summary
Query with sort key conditions lets you find items within a partition using filters on the sort key.
You always specify the partition key with '=' and can use operators on the sort key.
This makes your database queries faster and more precise.