0
0
DynamoDBquery~5 mins

Query by partition key in DynamoDB

Choose your learning style9 modes available
Introduction

We use query by partition key to quickly find all items that share the same main identifier in a DynamoDB table.

When you want to get all orders made by a specific customer using their customer ID.
When you need to find all messages in a chat room identified by a room ID.
When you want to retrieve all products in a category identified by a category ID.
When you want to fetch all events happening on a specific date stored as a partition key.
Syntax
DynamoDB
aws dynamodb query \
  --table-name TableName \
  --key-condition-expression "PartitionKeyName = :partitionkeyval" \
  --expression-attribute-values '{":partitionkeyval":{"S":"PartitionKeyValue"}}'
The partition key is the main key that DynamoDB uses to organize data.
You must provide the partition key value to get matching items.
Examples
This finds all orders where the CustomerID is '12345'.
DynamoDB
aws dynamodb query \
  --table-name Orders \
  --key-condition-expression "CustomerID = :custid" \
  --expression-attribute-values '{":custid":{"S":"12345"}}'
This fetches all messages in the chat room with ID 'roomA'.
DynamoDB
aws dynamodb query \
  --table-name Messages \
  --key-condition-expression "RoomID = :roomid" \
  --expression-attribute-values '{":roomid":{"S":"roomA"}}'
Sample Program

This query gets all products in the 'electronics' category.

DynamoDB
aws dynamodb query \
  --table-name Products \
  --key-condition-expression "CategoryID = :catid" \
  --expression-attribute-values '{":catid":{"S":"electronics"}}'
OutputSuccess
Important Notes

Query by partition key is fast because DynamoDB uses the partition key to find data directly.

You cannot query by partition key alone if your table uses a composite key and you want to filter by sort key; you need to include conditions for the sort key too.

Summary

Query by partition key fetches all items with the same main key value.

It is efficient and fast because DynamoDB organizes data by partition key.

You provide the partition key value in the query to get matching items.