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:提升讀取效能

本章總結

  • 理解核心概念與原理
  • 掌握實作方法與技巧
  • 熟悉常見問題與解決方案
  • 能夠應用於實際專案

延伸閱讀

  • 官方文件與 API 參考
  • GitHub 開源專案範例
  • 相關技術書籍與課程
  • 社群討論與技術部落格

實作範例

基礎範例

# 本節提供一個完整的實作範例
# 讓你能夠將所學應用到實際專案中

步驟說明

  1. 初始化:設定開發環境與必要工具
  2. 資料準備:收集與整理所需資料
  3. 核心實作:實作主要功能與邏輯
  4. 測試驗證:確保功能正確運作
  5. 最佳化:調整效能與使用者體驗

常見錯誤

| 錯誤類型 | 可能原因 | 解決方法 | |---------|---------|---------| | 編譯錯誤 | 語法問題 | 檢查程式碼語法 | | 執行錯誤 | 環境問題 | 確認相依套件已安裝 | | 邏輯錯誤 | 演算法問題 | 逐步除錯與測試 | | 效能問題 | 效率問題 | 使用效能分析工具 |

程式碼範例

# 範例程式碼
import sys

def main():
    # 主程式邏輯
    print("Hello, World!")

if __name__ == "__main__":
    main()

相關資源

  • 官方文件
  • API 參考手冊
  • 開源專案範例
  • 技術社群討論

会員限定無料チュートリアル

このチャプターは登録会員限定の無料コンテンツです!ログインまたは登録してすぐにロックを解除してください。

今すぐログイン / 登録