iT邦幫忙

2022 iThome 鐵人賽

DAY 12
0

Key-Value 的結構相信大家都不陌生,Associative Array、Map、Dictionary、Hash Map......等資料結構出現在各語言,Key-Value Database 顧名思義就是使用 Key-Value 的概念做為基礎。每個 Key 會對應到一個 Value,多個 Key-Value 可以被分在多個集合,這些集合稱之為 Namespace 或 Bucket,在 Bucket 中每個 Key 必須唯一,而 Key-Value Database 就由這些 Buckets 組成。

https://ithelp.ithome.com.tw/upload/images/20220820/20151137mZQtfBQE0O.png

不像關聯式資料庫一張表有多個欄位的設計,Key-Value Database 不需要預先在資料庫定義好所有欄位名稱及其型別才能進行資料存取,因此在當資料模型有欄位上的異動時也不像關聯式資料庫需要調整 Schema,更可以有 [student:1:score]=95[student:2:score]='A'同時存在不同型別的設計。在每個 Namespace 中 Key 必定唯一,而 Value 不限定型別但資料不可過大(限制視你使用的資料庫類型而異),常見的設計會使用有意義的組合 Key 搭配不過長的 Value,

Key Value
student:1:name 'Stuart'
student:1:gender 'Male'
student:1:birthday '2000-01-01'
student:1:class '3A'
student:1:score 95
student:2:name 'Kevin'
student:2:gender 'Male'
student:2:birthday '2002-04-18'
student:2:class '1B'
student:2:score 'A'

或是使用簡單的資料結構,以序列化後的格式(如 Json)存放。

Key Value
student:1:profile {"name":"Stuart","gender":"Male","birthday":"2000-01-01"}
student:1:class {"class":"3A","score":95"}
student:2:profile {"name":"Kevin","gender":"Male","birthday":"2002-04-18"}
student:2:class {"class":"1B","score":"A"}

當今天沒有複雜資料結構和關聯需求時,使用關聯式資料庫並不會享受到它控管資料約束等功能所帶來優勢,相較之下,選擇 Key-Value Database 則可以享受它提供單純且直白的資料存放方式的效益。從前幾天的CAP理論可知,C、A和P無法兼顧,Key-Value Database 選擇犧牲強一致性,採用最終一致性。

Key-Value Database 對資料的所有操作都由 Key 的角度出發,因此當你不知道 Key 時就無法查詢資料了;這個限制也表示「查詢所有生日是2022-01-01的員工編號」這類以 Value 為出發點的操作不在 Key-Value Database 的支援範圍。當然,你可以選擇很暴力的把所有資料掃過一次找出你要的結果,但顯然這不是一個有效率的好做法。有的 Key-Value Database 會提供建立索引或是全文檢索的功能,它會紀錄擁有特定 Value 的所有 Key,這樣就可以透過 Value 反查 Key。

Index
2022-01-01 ‘employee:29183:birthday’,‘employee:19372:birthday’
2022-01-02 ‘employee:286:birthday’,‘employee:7241:birthday’,‘employee:77739:birthday’,‘employee:52812:birthday’
2022-01-05 ‘employee:20519:birthday’
2022-01-07 ‘employee:9928:birthday’,‘employee:18525:birthday’,‘employee:37321:birthday’,‘employee:82909:birthday’,‘employee:67621:birthday’
...... ......
2022-12-30 ‘employee:90013:birthday’
2022-12-31 ‘employee:86620:birthday’,‘employee:29186:birthday’

上一篇
[Day 11] Consistent Hashing 一致性雜湊
下一篇
[Day 13] Key-Value Database: 簡介
系列文
NoSQL: Not Only SQL30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言