Appearance
DynamoDB Query Patterns
Query vs Scan (CRITICAL)
Query (✅ Use this):
- Requires partition key
- Optionally filters by sort key
- Charges only for items examined
- Thường một chữ số mili giây (tài liệu AWS: "single-digit millisecond performance at any scale"; không phải cam kết độ trễ cho từng Query)
Scan (❌ Avoid in production):
- Reads entire table
- Applies filter AFTER reading (wasteful)
- Charges for ALL items read
- Slow, expensive, doesn't scale
Example:
javascript
// Node.js (SDK v3). dynamodb-local: docker run -p 8000:8000 amazon/dynamodb-local
import { DynamoDBClient, CreateTableCommand } from '@aws-sdk/client-dynamodb'
import { DynamoDBDocumentClient, BatchWriteCommand, QueryCommand, ScanCommand } from '@aws-sdk/lib-dynamodb'
const client = new DynamoDBClient({ region: 'us-east-1', endpoint: 'http://localhost:8000', credentials: { accessKeyId: 'x', secretAccessKey: 'x' } })
const ddbDocClient = DynamoDBDocumentClient.from(client)
// Tạo bảng Orders và nạp 4 000 item (200 user × 20 đơn)
await client.send(new CreateTableCommand({
TableName: 'Orders',
BillingMode: 'PAY_PER_REQUEST',
AttributeDefinitions: [{ AttributeName: 'userId', AttributeType: 'S' }, { AttributeName: 'orderDate', AttributeType: 'S' }],
KeySchema: [{ AttributeName: 'userId', KeyType: 'HASH' }, { AttributeName: 'orderDate', KeyType: 'RANGE' }]
}))
for (let u = 0; u < 200; u++) {
const items = Array.from({ length: 20 }, (_, o) => ({ PutRequest: { Item: { userId: 'USER#' + u, orderDate: `2025-0${1 + (o % 9)}-${10 + o}`, status: o % 4 ? 'done' : 'pending', pad: 'x'.repeat(300) } } }))
await ddbDocClient.send(new BatchWriteCommand({ RequestItems: { Orders: items } }))
}
// ✅ Query (requires PK, fast)
const q = await ddbDocClient.send(new QueryCommand({
TableName: 'Orders',
KeyConditionExpression: 'userId = :uid AND orderDate > :date',
ExpressionAttributeValues: { ':uid': 'USER#123', ':date': '2025-01-01' },
ReturnConsumedCapacity: 'TOTAL'
}))
console.log('Query', q.Count, q.ScannedCount, q.ConsumedCapacity.CapacityUnits) // 20 20 1
// ❌ Scan (reads all, slow); mỗi trang tối đa 1 MB nên phải phân trang
let rcu = 0, scanned = 0, key
do {
const r = await ddbDocClient.send(new ScanCommand({
TableName: 'Orders',
FilterExpression: 'userId = :uid AND orderDate > :date',
ExpressionAttributeValues: { ':uid': 'USER#123', ':date': '2025-01-01' },
ReturnConsumedCapacity: 'TOTAL',
ExclusiveStartKey: key
}))
rcu += r.ConsumedCapacity.CapacityUnits; scanned += r.ScannedCount; key = r.LastEvaluatedKey
} while (key)
console.log('Scan', scanned, rcu) // 4000 170
// Đo trên dynamodb-local (item ~350 B, eventually consistent): Query đọc 20 item = 1 RCU; Scan đọc 4 000 item = 170 RCU, vẫn chỉ trả 20 item
// RCU tính theo kích thước dữ liệu đọc (mỗi 4 KB), không phải mỗi itemQuy tắc: nếu cần truy vấn thường xuyên theo thuộc tính không phải khoá, thiết kế GSI (hoặc khoá/bảng khác) thay vì Scan; Scan chỉ cho việc hiếm (đo ở trên: 170 RCU để trả 20 item).
GSI Overloading Pattern
Problem: Multiple access patterns, limited GSIs (default quota 20 per table, can be raised via Service Quotas)
Solution: Overload GSI with multiple entity types
text
// Main table
PK SK GSI1PK GSI1SK
─────────────────────────────────────────────────────────────────
USER#123 METADATA EMAIL#john@... USER#123
USER#123 ORDER#001 STATUS#pending ORDER#001
PRODUCT#456 METADATA CATEGORY#tech PRODUCT#456
// Access pattern 1: Get user by userId (main table)
// KeyConditionExpression: PK = 'USER#123' AND SK = 'METADATA'
// Access pattern 2: Get user by email (GSI1)
// IndexName: 'GSI1', KeyConditionExpression: GSI1PK = 'EMAIL#john@...'
// Access pattern 3: Get orders by status (GSI1, different entity type)
// IndexName: 'GSI1', KeyConditionExpression: GSI1PK = 'STATUS#pending'
// Access pattern 4: Get products by category (GSI1, different entity type)
// IndexName: 'GSI1', KeyConditionExpression: GSI1PK = 'CATEGORY#tech'Benefit: 1 GSI supports 3+ access patterns
Sparse GSI Pattern
Problem: Only 5% of users are premium, but need to query them frequently
Solution: GSI that only includes items with attribute
text
Main table
PK SK subscriptionType GSI1PK GSI1SK
──────────────────────────────────────────────────────────────
USER#123 METADATA premium PREMIUM USER#123 ← In GSI
USER#456 METADATA (none) (none) (none) ← NOT in GSI
GSI1 chỉ chứa 5% item (premium user) trong ví dụ nàyjavascript
// Node.js (SDK v3): chạy sau khi có ddbDocClient (mục Query vs Scan) và bảng Users có GSI1 (GSI1PK, GSI1SK)
const params = {
TableName: 'Users',
IndexName: 'GSI1',
KeyConditionExpression: 'GSI1PK = :type',
ExpressionAttributeValues: { ':type': 'PREMIUM' }
}
await ddbDocClient.send(new QueryCommand(params))Benefits:
- ✅ GSI chỉ chứa ~5% item trong ví dụ này (rẻ hơn về lưu trữ; tỉ lệ thật tuỳ dữ liệu)
- ✅ Faster queries (smaller index)
- ✅ Lower WCU (only write 5% to GSI)
Filter Expression vs Key Condition
Key Condition (✅ Efficient):
- Filters using partition key and sort key
- Charges only for matching items
- Uses index
Filter Expression (⚠️ Less efficient):
- Filters AFTER reading items
- Charges for ALL items read
- But still faster than Scan (uses index to narrow down first)
javascript
// Node.js (chỉ phần tham số, minh hoạ, không chạy độc lập). `status` là từ khoá dành riêng nên phải dùng #status
// ✅ Key Condition (best)
{
KeyConditionExpression: 'PK = :pk AND SK BETWEEN :start AND :end',
// Reads only items in range
}
// ⚠️ Key Condition + Filter Expression (OK)
{
KeyConditionExpression: 'PK = :pk AND SK BETWEEN :start AND :end',
FilterExpression: '#status = :status', // Filters after reading range
ExpressionAttributeNames: { '#status': 'status' },
// Reads items in range, charges for all, returns filtered subset
// Đo: Query đọc 20 item, lọc còn 5 item, vẫn 1 RCU như không lọc
}
// ❌ Filter Expression only (bad)
{
FilterExpression: '#status = :status',
ExpressionAttributeNames: { '#status': 'status' },
// Scans entire table (like Scan)
}Rule: Always use KeyConditionExpression with partition key.
Pagination (Limit + LastEvaluatedKey)
Don't use Scan with large limits:
javascript
// ❌ Bad: huge Limit is pointless (each Scan/Query page is capped at 1 MB); still must paginate
const params = {
TableName: 'Orders',
Limit: 1000000
}Use pagination:
javascript
// Node.js (SDK v3): chạy sau khi tạo ddbDocClient và bảng Orders ở mục Query vs Scan
import { QueryCommand } from '@aws-sdk/lib-dynamodb'
let items = []
let lastKey = undefined
do {
const params = {
TableName: 'Orders',
KeyConditionExpression: 'userId = :uid',
ExpressionAttributeValues: { ':uid': 'USER#123' },
Limit: 100, // Page size
ExclusiveStartKey: lastKey
}
const result = await ddbDocClient.send(new QueryCommand(params))
items = items.concat(result.Items)
lastKey = result.LastEvaluatedKey
} while (lastKey) // Continue until no more pagesBatch Operations (Reduce Round-Trips)
BatchGetItem (read up to 100 items):
javascript
// Node.js (SDK v3), minh hoạ không chạy độc lập: giả định bảng Users khoá PK/SK; ddbDocClient tạo ở mục Query vs Scan
import { BatchGetCommand } from '@aws-sdk/lib-dynamodb'
const params = {
RequestItems: {
'Users': {
Keys: [
{ PK: 'USER#123', SK: 'METADATA' },
{ PK: 'USER#456', SK: 'METADATA' },
// ... up to 100 keys
]
}
}
}
const result = await ddbDocClient.send(new BatchGetCommand(params))
// 1 round-trip for up to 100 items (16 MB max) — must retry UnprocessedKeys with backoffBatchWriteItem (write up to 25 items):
javascript
// Node.js (SDK v3), minh hoạ không chạy độc lập: giả định bảng Orders khoá PK/SK; ddbDocClient tạo ở mục Query vs Scan
import { BatchWriteCommand } from '@aws-sdk/lib-dynamodb'
const params = {
RequestItems: {
'Orders': [
{ PutRequest: { Item: { PK: 'USER#123', SK: 'ORDER#001', total: 10 }}},
{ PutRequest: { Item: { PK: 'USER#123', SK: 'ORDER#002', total: 20 }}},
// ... up to 25 items
]
}
}
await ddbDocClient.send(new BatchWriteCommand(params))Conditional Writes (Optimistic Locking)
Prevent concurrent updates:
javascript
// Node.js (SDK v3), chạy sau khi tạo ddbDocClient (mục Query vs Scan) và bảng Users khoá PK/SK có item USER#123
import { UpdateCommand } from '@aws-sdk/lib-dynamodb'
// Update only if version matches (optimistic locking)
const params = {
TableName: 'Users',
Key: { PK: 'USER#123', SK: 'METADATA' },
UpdateExpression: 'SET balance = balance - :amount, version = version + :inc',
ConditionExpression: 'version = :expectedVersion',
ExpressionAttributeValues: {
':amount': 100,
':inc': 1,
':expectedVersion': 5 // Fail if version != 5
}
}
try {
await ddbDocClient.send(new UpdateCommand(params))
} catch (err) {
if (err.name === 'ConditionalCheckFailedException') {
// Version conflict - retry with latest version
}
}Projection Expression (Reduce Transfer Size)
Don't fetch entire item if you need only a few attributes:
javascript
// Node.js (SDK v3): chỉ phần tham số của GetCommand, minh hoạ không chạy độc lập
// ❌ Bad: Fetch entire 100KB item
const params = {
TableName: 'Users',
Key: { PK: 'USER#123', SK: 'METADATA' }
}
// ✅ Good: Fetch only needed attributes
const params = {
TableName: 'Users',
Key: { PK: 'USER#123', SK: 'METADATA' },
ProjectionExpression: 'email, #n', // Only email and name
ExpressionAttributeNames: { '#n': 'name' } // 'name' is reserved keyword
}Benefits:
- ❌ Does NOT lower RCU (consumption is based on full item size); only reduces network transfer
- ✅ Faster (less data transfer)
- ✅ Lower bandwidth costs
Phải nhớ:
- Dùng
Queryvới partition key (và sort key khi có) thay choScan; đo trên dynamodb-local: 1 RCU so với 170 RCU cho cùng 20 item. FilterExpressionlọc SAU khi đọc: RCU tính theo dữ liệu đã đọc;ProjectionExpressioncũng không giảm RCU.- Tên thuộc tính trùng từ khoá dành riêng (
status,name) phải dùng#aliasquaExpressionAttributeNames.