1.3.4 DynamoDB Keys & Indexing
DynamoDB Keys and Indexing
Primary Key Types
| Type | Cấu trúc | Ví dụ |
|---|
| Simple (Partition Key) | PK only | user_id |
| Composite | PK + Sort Key (SK) | user_id + order_date |
- PK: Xác định partition lưu trữ
- SK: Cho phép range queries trong cùng partition
GSI vs LSI
| GSI (Global Secondary Index) | LSI (Local Secondary Index) |
|---|
| PK/SK | Khác main table | Cùng PK, SK khác |
| Throughput | RCU/WCU riêng | Dùng chung main table |
| Consistency | Eventually Consistent only | Strongly + Eventually |
| Tạo khi nào | Bất kỳ lúc nào | Chỉ lúc tạo table |
| Limit | 20 per table | 5 per table |
| Size limit | Không giới hạn | 10GB per partition key |
GSI — Global Secondary Index
Main Table:
PK: user_id | SK: order_date | status | amount
GSI (status-index):
PK: status | SK: order_date
→ Query tất cả orders theo status
- GSI là “bản copy” của table với key schema khác
- Write vào main table → async replicate sang GSI
- GSI throttling có thể ảnh hưởng main table writes
LSI — Local Secondary Index
Main Table:
PK: user_id | SK: order_date | status | amount
LSI (user-amount-index):
PK: user_id | SK: amount
→ Query orders của 1 user, sort theo amount
- Cùng partition key với main table
- Cho phép strongly consistent reads
- Item collection size limit: 10GB per partition key value
Projected Attributes
| Projection Type | Mô tả | RCU |
|---|
| KEYS_ONLY | Chỉ PK + SK | Ít nhất |
| INCLUDE | Keys + specified attributes | Trung bình |
| ALL | Tất cả attributes | Nhiều nhất |
- Nếu query attribute không có trong projection → DynamoDB fetch từ main table (tốn thêm RCU)
Index Design Best Practices
- Tạo GSI cho access patterns khác PK chính
- Dùng sparse index: chỉ items có attribute mới xuất hiện trong index
- Overloading GSI: dùng generic attribute names (
GSI1PK, GSI1SK) cho multiple entity types
Exam Tip: GSI = flexible nhưng eventually consistent only. LSI = strongly consistent nhưng phải tạo lúc tạo table. GSI throttling → backpressure lên main table. Cần strongly consistent index → LSI.