1x-Chen
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Database Note ## 3-Tiers architecture * **Presentation Tier**: GUI, Web interface * **Application Server / Web Server**: Application programs, web pages * Add, delete, update data in the data tier * communicates with data tier using API calls * **Database Server**: DBMS **Advantages:** 1. Each tier runs on its own infra. 2. Can be developed simultaneously 3. Can be scaled and updated 4. Faster development 5. Improved scalability, reliability, security ## 完整性法則(Integrity rule) * 實體完整性:主鍵或複合主鍵的任一屬性不可為Null * 參考完整性:當外來鍵參考到其他關聯的候選鍵時,其值必須存在 * 定義域完整性法則 ## 集中式資料庫 vs 分散式資料庫 ### 集中式資料庫 (Centralized Database, CDB) 將資料集中儲存在一台資料庫伺服器 * 容易管理資料但是風險較高 * 資料傳輸率容易受網路流量影響 * 所有資料都集中給一台伺服器處理,所以伺服器的負擔很重 ### 分散式資料庫 (Decentralized Database, DDB) 將資料依照特性分散儲存在不同的資料庫伺服器,再以網路將這些伺服器連結起來 ![](https://i.imgur.com/O1u2jBx.png) ➤分散式資料庫(Distributed Database, DDB):當資料儲存在分散式資料庫時,在邏輯上是屬於同一個資料庫系統,但是實際上資料是分散儲存在以網路連接的不同資料庫伺服器上,這樣可以**分散風險**,**資料傳輸率不易受網路流量影響**。 ➤分散式資料庫管理系統(Distributed Database Management System, DDBMS):是管理分散式資料庫的軟體,提供資料的分散儲存,但是使用者並不會認為他是在存取分散儲存的資料,對於使用者來說,感覺仍然是一個完整的資料庫,這是分散式資料庫系統很重要的特性,稱為「**通透性(Transparent)**」。 * Advantages 1. 增加資料庫系統的執行效能 2. 提高可靠性和可用性 3. 更高的彈性和可擴充性 ## CAP Thereom 從一個簡單的小系統開始,這個系統有個小資料庫,一切單純而美好。但隨著系統的使用者與資料越來越多,小系統慢慢變大,資料庫也開始逐漸不堪負荷。於是我們開始幫資料庫升級(更多的RAM、更多的空間),但硬體的升級是有極限的,終究還是遇到了瓶頸。 ![](https://i.imgur.com/e8LhNho.png) --- **CAP定理** * Consistency 一致性: 使用者讀到的“總是”最新的資料 * Availability 可用性: 使用者的請求“總是”可以獲得回應,也就是可以正常的讀寫 * Partition tolerance 分區容錯性: 就算網路出現問題導致資料分區,整個系統仍然要可以繼續運作 CAP定理:**在分散式系統中,這三個特性只能同時滿足兩個**,必須做出trade-off * Note CA不算是一種選擇,因為若同時要滿足這兩個條件,就絕對不能出現資料分區,也就是網路狀態必須是完美的(不現實) ![](https://i.imgur.com/jwiLRZa.png) ### CP vs AP 先看看滿足CP(一致性、分區容錯性)的系統如何運作。使用者連線到其中一個資料庫,想要讀取或寫入資料。若此時發現無法與另一個資料庫同步,使用者的請求就會失敗! ![](https://i.imgur.com/XEGAg6V.png) 再來看看滿足AP(可用性、分區容錯性)的系統。使用者連線到其中一個資料庫想要更新資料,此時該資料庫無法同步另一個資料庫。但它仍然更新了這筆資料並告知使用者更新成功。 若很不幸地,下次使用者連線到另一個資料庫想要拿資料,就會拿到舊的資料!我們保證了系統的A(可用性),讓使用者總是能得到回應。但犧牲了資料的C(一致性)。 ![](https://i.imgur.com/4ARj3q0.png) ### 最終一致性 (Eventually Consistency) 我們把CAP定理所定義的一致性稱為**強一致性(strong consistency)**。適合處理像是金錢、付款這種對資料同步高度要求的任務。但相對的,擴展性、可用性就會比較侷限(想像一下,若資料庫的數量持續地增加,同步所有資料的成本也會不斷上升)。 與強一致性相對的是所謂的最終一致性(eventually consistency)。當使用者更新某筆資料時,也許因為網路暫時中斷或延遲,沒有即時同步到另一個資料庫。我們還是讓其他使用者可以繼續存取資料(不是最新的也沒關係),但最終,我們保證這筆資料一定會同步(最後的結果還是對的)。 ![](https://i.imgur.com/FZtWUtk.png) resource: https://medium.com/%E5%BE%8C%E7%AB%AF%E6%96%B0%E6%89%8B%E6%9D%91/cap%E5%AE%9A%E7%90%86101-3fdd10e0b9a ### Summary of CAP **AP Database — 犧牲一致性的分散式資料庫** 在分區容忍的前提下(因為都已經採用分散式架構了),犧牲一致性來提高可用性(盡可能每次都得到回應),不過雖然犧牲了一致性,卻仍可以達到最終一致性(Eventual Consistency,例如總統大選開票時每家新聞台的即時票數都不一致,但在選舉結束後的票數還是會達成一致。),適合在需要快速讀寫,但資料對於一致性的需求較低的場景,例如臉書或各大媒體平台的按讚系統。 例如:Amazon DynamoDB **CP Database — 犧牲可用性的分散式資料庫** 在分區容忍的前提下,依然可以得到最新版本的資料,常用於貼文系統、訊息系統等不能犧牲一致性的系統。 例如:Google BigTable、MongoDB、分散式的 RDBMS ## Scaling & Availability 1. RDBMS 怎麼做到 Scaling **Sharding** ![](https://i.imgur.com/qtBpoMW.png) 2. RDBMS 怎麼做到 High Availability **Replication** ![](https://i.imgur.com/fJU0XnB.png) * Master-Slave ![](https://i.imgur.com/FdZU3vu.png) * Master-Master ![](https://i.imgur.com/LjCJGv8.png) ## NoSQL NoSQL解決的問題: * 容易擴展的設計架構,因為沒有關聯性,相較於RDBMS更容易scaling * 簡單快速的達到高可用性 * 容易進行Schema的變更,因為根本沒有Schema,適合時常變更架構的系統 **Drawbacks** * 沒有固定的 Schema : 這點其實嚴格來說可以是優點也可以是缺點,得看需求來定論。 * 關聯式資料庫常見的 Transaction 與 JOIN 也就非常難在 NoSQL 實踐。 * 資料量不夠大時,其實效能普遍比 RDBMS 來要差 ### RDBMS vs NoSQL **RDBMS (Relational Database Management System)** * 由Table組成,其中row代表一筆資料,column代表資料欄位名稱 * Schema必須事先定義好 * 可以使用JOIN來連結多個資料表,做比較複雜的查詢 * ACID * Atomicity: 交易只有全部執行&全部不執行 * Consistency: 交易執行完,資料庫的狀態是一致的 * Isolation: 此交易不應被其他同步執行的交易干擾 * Durability: Commit後,即使日後系統當機或損毀,其對資料庫所做的動作永久有效 * SQL * 不太能做水平擴充(要的話需要像上述做sharding) * RDBMS 具有 ACID 的特性,因此當一個 transaction 要修改某個資料時,會將其他也要操作這個資料的 transaction 先 lock 住,以防 race condition,接著等到這個 transaction 做完後,才同意讓其他 transaction 繼續進行下去。所以這樣的機制下,會降低到資料庫的效能。 * 假設今天要將 RDBMS 做 horizontal scaling 的擴充,這時需要被 lock 的 Table 可能分佈在不同的 server 上面,這時要找出哪些 Table 要被 lock,以及該 Table 在哪一台 server 上面,都會嚴重降低資料庫效能,而且系統的複雜度也遠比單一台 server 要複雜許多! **NoSQL (Not only SQL)** * BASE原則 * BA: Basically Available - 只保證一定的可用性 * S: Soft-state - 不保證在同時有讀寫時資料是一致的 * E: Eventually consistent * 資料庫由collection組成 * collection中每筆資料為一份document,document的資料格式不需一致 * 常用於分散式系統 (支援垂直擴充和水平擴充) --- **為什麼使用 RDBMS?** 需要確保 ACID 特性的情境。RDBMS 類型的資料庫,保證了 ACID,保證了資料的一致性。舉例在金融類型的應用,你會希望匯入匯出的錢,能夠同步一致的更新到資料庫上,以防重複扣款或是餘額顯示錯誤等等的狀況。而 NOSQL 是沒有保證 ACID 的,所以在這種情況下,RDBMS 相較於 NOSQL 更適合。 **為什麼使用 NOSQL?** 由於 NOSQL 的 schema 不需要固定,且資料可以為任意結構。所以在 schema 需要頻繁變動或者是 schema 不固定的時候,NOSQL 提供更有彈性的開發。比如在開發初期,schema 會需要頻繁更新,這時候 NOSQL 就比較適合。 需要儲存大量資料,利用分散式系統以及雲端儲存的時候。由於 NOSQL 相較於 RDBMS 更容易做 horizontal scaling,且本身的設計就是分散式系統的設計。因此對於未來有大量擴充需求的系統,會更容易的去擴充,且擴充的成本也較低。 ### 資料庫推薦與適合場域 ![](https://i.imgur.com/Y7MNdTY.png) 1. Unbounded: 指的是在分散式架構中,可搜尋的容量為無限 2. HDD-Size: 之的是在single node 情況下,可搜尋的容量為硬碟容量 3. Ad-hoc: 即時查詢,如sql中的 select ..from aDB where [condictions..] 4. Analytics: 只的是在query 的時候可具備資料分析的能力 5. OLTP((online transaction processing): 網路交易process ## Cache vs Buffer **Cache讀取,Buffer寫入** * Cache 1. A cache is a high-speed memory that is used to **store frequently accessed data**. 2. The cache stores a subset of data that is expected to be needed soon, based on a prediction algorithm, to reduce latency and increase throughput. 3. The cache typically has a smaller capacity than the primary storage it serves, and it is managed by a cache replacement policy that decides which data to discard when the cache is full. * Buffer 1. A temporary storage area that holds data that is being transferred between two devices or processes 2. **Absorb the difference between the transfer rates** of the source and destination, enabling the data transfer to occur without interruptions 3. The buffer acts as a **queue of data**, storing a block of data until the next block is available, ensuring that the data flow remains uninterrupted. Cache is used to speed up access to frequently used data, while the buffer is used to manage the transfer of data between two devices or processes. ## Database indexing * Full Table Scan: 當我們想要從資料庫找符合某特定條件的資料,資料庫的標準程序是一行一行檢查,看看資料是否符合條件 * Indexing 1. 預設會把主鍵加上索引,假設有一張資料表A,A的ID欄位被標上索引,會有一個A'的資料表儲存了A的所有ID 2. 如果要找A中的資料,則會到A'中快速的(i.e. binary search)找到對應的ID,再到A資料表對應到完整的資料 3. 通常A'都會以Hash / B-Tree實作 Indexes can be created on one or more columns in a table, and they can be either clustered or non-clustered. A clustered index determines the physical order of the data in the table, while a non-clustered index is a separate structure that points to the data in the table.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully