DynamoDB 與資料模型

Vibe Prompt

「幫我設計 DynamoDB 表格儲存電商訂單資料:支援依使用者查詢、依日期查詢、依狀態查詢。」

表格設計

Orders Table:
  Partition Key: user_id (String)
  Sort Key: order_id (String)
  
  GSI 1: status-created_at-index
    Partition Key: status (String)
    Sort Key: created_at (String)
  
  GSI 2: created_at-index
    Partition Key: created_at (String)

CRUD 操作

# 查詢使用者訂單
response = table.query(
    KeyConditionExpression=Key('user_id').eq('user_123')
)

# 依狀態查詢(使用 GSI)
response = table.query(
    IndexName='status-created_at-index',
    KeyConditionExpression=Key('status').eq('pending')
)

# 寫入
response = table.put_item(Item={
    'user_id': 'user_123',
    'order_id': 'order_456',
    'amount': 99.99,
    'status': 'pending',
    'created_at': '2025-06-30T10:00:00Z'
})

# 更新
response = table.update_item(
    Key={'user_id': 'user_123', 'order_id': 'order_456'},
    UpdateExpression='SET #st = :st',
    ExpressionAttributeNames={'#st': 'status'},
    ExpressionAttributeValues={':st': 'completed'}
)

最佳實踐

  • ✅ 避免 Hot Partition:Partition Key 要有足夠的區分度
  • ✅ 使用 Pay Per Request:流量不穩定時最省錢
  • ✅ 設定 TTL:自動過期舊資料
  • ✅ 搭配 DAX:提升讀取效能

會員專屬免費教學

本章節為註冊會員專屬的免費開放內容!請先登入或註冊會員,即可立即解鎖閱讀。

立即登入 / 註冊