# Chapter 15 - DynamoDB
###### tags: `大話AWS雲端架構`
### <font color="#5662F6">講者:Andrew
### 日期:2021/11/03</font>
## 15.1 DynamoDB
- Amazon DynamoDB 是一個全受管、無伺服器、鍵值 NoSQL 資料庫,旨在以任何規模執行高效能應用程式。
- DynamoDB 提供內建安全性、持續備份、自動多區域複寫、記憶體內快取和資料匯出工具。
- 適合不需對資料做複雜的join、容易變動資料、且需要快速回復資料等的一個資料庫
## 15.2 核心組件
Table:資料表, Item:一筆資料, Key-Attribute:鍵值, Value:Attribute裡可能有多個Value
- DynamoDB為分散式資料庫,會依照Item內容將資料分散到多個Partition(分區)

## 15.3 資料分散與排序方式
- Key是資料如何分散到不同Partition的關鍵
- DynamoDB設計出了兩種類型的Key
- **Partition Key**: 用來決定資料要分佈在那些分區上,ex:以用戶資料中姓氏的欄位作為分區的依據
- **Sort Key**: 進入分區後,為了達到快速檢索,必須先將分區中的資料排序過,因此以Sort Key為依據幫資料做排序。ex:以用戶的年齡為sort key,排序分區內的資料。
## 15.4 增強資料讀取效率的二級索引
### 15.4.1 Local Secondary Index & Global Secondary Index
- DynamoDB提供兩種[Secondary Index](https://docs.aws.amazon.com/zh_tw/amazondynamodb/latest/developerguide/SecondaryIndexes.html)(二級索引),來讓我們對資料重作分區與排序。
- 何時使用:不滿意Partition Key或Sort Key配置時,想重設或是增設。
- [Ref](https://medium.com/@kennith/dynamo-db-lsi-and-gsi-b685ff6e2d3)
#### 1. **LSI** (Local Secondary Index)
- 只想改動Sort Key
- 只能一開始在Table建立時同時建立,之後無法對現有的資料表新增或是修改、刪除LSI。
- Partition Key都相同(因為是同一分區的資料)
#### 2. **GSI** (Global Secondary Index)
- 只更改Partition Key(簡單) or Partition Key & Sort Key都更改(複雜)
- 可在建立資料表的同時建立、也可以將新的GSI新增至現有的資料表,或刪除現有的GSI。
## 15.5 按讀寫量來計費
- 除了用儲存空間和流量外,還可用Read-Write Units(讀寫單位)來計價
- 每一筆資料(Item)
- [定價](https://aws.amazon.com/tw/dynamodb/pricing/on-demand/)
## 15.5 按照讀寫量來計費
- 最終一致性(ECR):對於已改變的資料讀取,最終都能取得已更新的資料,但不保證能立即取得已更新的資料。這個是Default。
- 強制一致性(SCR):一定會反應最近寫入的結果。
-
[Amazon DynamoDB 的 Consumed Units 注意事項](https://medium.com/fcamels-notes/amazon-dynamodb-%E7%9A%84-consumed-units-%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A0%85-e1fbda5687b4)
## 15.6 兩大備份方案
- On-Demand Backup and Restore(隨需備份):讓用戶快速地手動備份,備份時間自訂,只能還原到有備份的時間點。
- Point-in-Time Recovery(時間點備份): AWS自動備份,可以把資料還原到過去的35天內。
DynamoDB資料存取方式與傳統資料庫不同,採用IAM的認證方式來做資料存取。
- 使用IAM來讓別人存取DynamoDB的資料。比如credential或role。
- [DynamoDB integration using AWS Cross-Account IAM Roles and AWS Access Keys.](https://rockset.com/docs/amazon-dynamodb/#:~:text=DynamoDB%20integration%20using%20AWS%20Cross-Account%20IAM%20Roles%20and%20AWS%20Access%20Keys.)
- [Use AWS IAM to Create a User with Permission for DynamoDB](https://egghead.io/lessons/aws-use-aws-iam-to-create-a-user-with-permission-for-dynamodb)
## 15.7 考題
## 15.8 整體架構圖

參考資料:
- https://rickhw.github.io/2016/08/17/AWS/Study-Notes-DynamoDB/