AWS DynamoDB: Query Items by Partition Key
Query DynamoDB tables by partition key using aws dynamodb query with key conditions, filter expressions, and projection.
DynamoDB Operations
Detailed Explanation
Querying DynamoDB Tables
The aws dynamodb query command retrieves items from a DynamoDB table using the partition key. Unlike scan, which reads every item, query is efficient because it directly looks up the partition.
Basic Query
aws dynamodb query \
--table-name Orders \
--key-condition-expression "customerId = :cid" \
--expression-attribute-values '{":cid": {"S": "customer-123"}}'
Query with Sort Key Range
aws dynamodb query \
--table-name Orders \
--key-condition-expression "customerId = :cid AND orderDate BETWEEN :start AND :end" \
--expression-attribute-values '{
":cid": {"S": "customer-123"},
":start": {"S": "2024-01-01"},
":end": {"S": "2024-12-31"}
}'
With Filter Expression
aws dynamodb query \
--table-name Orders \
--key-condition-expression "customerId = :cid" \
--filter-expression "orderTotal > :min" \
--expression-attribute-values '{
":cid": {"S": "customer-123"},
":min": {"N": "100"}
}'
Important: Filter expressions run after the query reads data, so they consume the same read capacity. Use key conditions for primary filtering.
Query a Global Secondary Index
aws dynamodb query \
--table-name Orders \
--index-name StatusIndex \
--key-condition-expression "orderStatus = :status" \
--expression-attribute-values '{":status": {"S": "pending"}}' \
--scan-index-forward false \
--limit 10
Projection (select specific attributes)
aws dynamodb query \
--table-name Orders \
--key-condition-expression "customerId = :cid" \
--expression-attribute-values '{":cid": {"S": "customer-123"}}' \
--projection-expression "orderId, orderDate, orderTotal"
Key Differences: Query vs Scan
| Aspect | Query | Scan |
|---|---|---|
| Requires partition key | Yes | No |
| Performance | Fast (targeted) | Slow (full table) |
| Cost | Low (reads only matching partition) | High (reads every item) |
| Use case | Known partition key | Ad-hoc exploration |
Use Case
Retrieving user-specific data from DynamoDB, looking up order histories, fetching session records, or querying time-series data within a partition key range.