0
0
DynamoDBquery~5 mins

Why Query is the primary read operation in DynamoDB

Choose your learning style9 modes available
Introduction

The Query operation in DynamoDB is the main way to find and read data quickly. It lets you get items by searching with a key, which is fast and efficient.

When you want to find all orders for a specific customer using their customer ID.
When you need to get all messages in a chat room by using the chat room ID.
When you want to retrieve all products in a category by using the category key.
When you want to fetch user details by their unique user ID.
Syntax
DynamoDB
query(
  TableName='YourTableName',
  KeyConditionExpression='PartitionKeyName = :value',
  ExpressionAttributeValues={
    ':value': {'S': 'YourKeyValue'}
  }
)

The KeyConditionExpression must include the partition key and can optionally include the sort key.

Query returns all items that match the key condition, making it faster than scanning the whole table.

Examples
Finds all orders for customer with ID 'C123'.
DynamoDB
query(
  TableName='Orders',
  KeyConditionExpression='CustomerID = :cid',
  ExpressionAttributeValues={':cid': {'S': 'C123'}}
)
Gets messages in chat room 'Room1' sent after a certain time.
DynamoDB
query(
  TableName='Messages',
  KeyConditionExpression='ChatRoomID = :chatid AND Timestamp > :time',
  ExpressionAttributeValues={
    ':chatid': {'S': 'Room1'},
    ':time': {'N': '1670000000'}
  }
)
Retrieves all products in the 'Books' category.
DynamoDB
query(
  TableName='Products',
  KeyConditionExpression='Category = :cat',
  ExpressionAttributeValues={':cat': {'S': 'Books'}}
)
Sample Program

This program connects to DynamoDB and queries the 'Users' table for all items where the UserID is 'U100'. It then prints each item found.

DynamoDB
import boto3

# Create DynamoDB client
client = boto3.client('dynamodb')

# Query to get all items with PartitionKey 'UserID' = 'U100'
response = client.query(
    TableName='Users',
    KeyConditionExpression='UserID = :uid',
    ExpressionAttributeValues={
        ':uid': {'S': 'U100'}
    }
)

# Print the items found
print('Items found:')
for item in response.get('Items', []):
    print(item)
OutputSuccess
Important Notes

Query is faster than Scan because it looks only at items with the specified key.

Query uses less read capacity units, saving cost and time.

Common mistake: Using Query without specifying the partition key will cause an error.

Summary

Query is the main way to read data by key in DynamoDB.

It is fast and efficient because it searches only relevant items.

Always specify the partition key in your Query to get results.