1.3.4 DynamoDB Keys & Indexing

DynamoDB Keys and Indexing

Primary Key Types

TypeCấu trúcVí dụ
Simple (Partition Key)PK onlyuser_id
CompositePK + 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/SKKhác main tableCùng PK, SK khác
ThroughputRCU/WCU riêngDùng chung main table
ConsistencyEventually Consistent onlyStrongly + Eventually
Tạo khi nàoBất kỳ lúc nàoChỉ lúc tạo table
Limit20 per table5 per table
Size limitKhông giới hạn10GB 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 TypeMô tảRCU
KEYS_ONLYChỉ PK + SKÍt nhất
INCLUDEKeys + specified attributesTrung bình
ALLTất cả attributesNhiề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.