NoSQL

ฐานข้อมูลที่ใช้ API/data model อื่นนอกจาก SQL — แบ่งเป็น 4 ประเภทหลัก แต่ storage engine ข้างในอาจเหมือน SQL DB ก็ได้

มุมมองของ Hussein Nasser

Database แบ่งเป็น 2 ส่วน:

  1. Frontend/API — SQL, document API, command-style
  2. Storage Engine/Backend — B-Tree, LSM-Tree, pages, bytes

Storage engine ไม่สนใจ data format — เห็นเป็น bytes ใน pages → “SQL vs NoSQL” จริง ๆ เป็นคำถามเกี่ยวกับ API + data model ที่ frontend ใช้

4 ประเภทของ NoSQL

(1) Key-Value Stores

  • ตัวอย่าง: Redis, DynamoDB, Memcached, etcd
  • โครงสร้าง: key → value (value อะไรก็ได้)
  • Use case: cache, session store, leaderboard, counter

(2) Document Stores

  • ตัวอย่าง: MongoDB, CouchDB, Couchbase, Elasticsearch
  • โครงสร้าง: collection ของ JSON/BSON documents
  • Schema-less หรือ flexible schema
  • Use case: content management, product catalog, user profile

(3) Wide-Column Stores

  • ตัวอย่าง: Cassandra, HBase, ScyllaDB, Bigtable
  • โครงสร้าง: row + dynamic columns (แต่ละ row ต่างกันได้)
  • ใช้ LSM-Tree → write-heavy excellent
  • Use case: time-series, IoT, logs

(4) Graph Databases

  • ตัวอย่าง: Neo4j, ArangoDB, Amazon Neptune
  • โครงสร้าง: nodes + edges with properties
  • Use case: social network, fraud detection, recommendation

ทำไมคนหนีไป NoSQL?

  1. Flexible schema — ไม่ต้อง migration ทุกครั้ง
  2. Horizontal scaling built-in (sharding)
  3. High write throughput — โดยเฉพาะ LSM-Tree DBs
  4. Eventual consistency รับได้ — สำหรับ social media, analytics

ทำไมหลายคนกลับมา SQL?

  1. JOIN ซับซ้อน — NoSQL ต้อง denormalize
  2. ACID transactions ข้าม collection
  3. PostgreSQL + JSONB — ได้ทั้ง SQL power + flexible schema
  4. เครื่องมือ + community ของ SQL ครบกว่า

คำแนะนำของ Hussein Nasser (2024+)

Workloadแนะนำ
DefaultPostgreSQL ก่อน
Time-seriesTimescaleDB (Postgres extension)
Flexible schemaMongoDB หรือ Postgres + JSONB
Global distribution + high writeCockroachDB / Cassandra
AnalyticsClickHouse + replicate จาก Postgres

Page Size ของ NoSQL Engines

DatabasePage SizeEngine
PostgreSQL8 KBBuilt-in heap
MySQL InnoDB16 KBInnoDB
MongoDB32 KBWiredTiger

Key Points

  • SQL vs NoSQL จริง ๆ คือเรื่อง API/data model ไม่ใช่ storage engine
  • 4 ประเภท: Key-Value, Document, Wide-Column, Graph
  • เส้นแบ่ง SQL/NoSQL เลือนลาง — MongoDB เพิ่ม transactions, Postgres มี JSONB
  • Default → Postgres แล้วค่อยเพิ่ม specialized DB ตามต้องการ
  • ย้ายไป NoSQL แล้ว develop แบบ relational = ปวดหัว
  • MongoDB — document store ที่วิเคราะห์ลึกใน course
  • Redis — key-value store
  • Memcached — key-value pure cache
  • Database Engines — B-Tree vs LSM-Tree ที่ NoSQL ใช้
  • CAP Theorem — NoSQL มักเป็น AP (availability + partition tolerance)
  • PostgreSQL — ทางเลือก default ก่อน NoSQL