Overview
NoSQL (“Not only SQL”) databases are non-relational data stores that provide flexible schemas and horizontal scalability. They are designed to handle large volumes of unstructured or semi-structured data.
Core Concepts
- Data Models:
- Document Store: Stores data as documents (e.g., JSON/BSON). Great for content management. (e.g., MongoDB).
- Key-Value Store: Simple map of keys to values. Extremely fast. (e.g., Redis).
- Column-Family Store: Stores data in columns rather than rows. Optimized for analytical queries. (e.g., Cassandra).
- Graph Database: Stores nodes and edges to represent relationships. (e.g., Neo4j).
- CAP Theorem: A distributed system can only provide two of the following three:
- Consistency: Every read receives the most recent write.
- Availability: Every request receives a response (success or failure).
- Partition Tolerance: The system continues to operate despite network partitions.
- Horizontal Scaling (Sharding): Distributing data across multiple servers to handle more load.
Code Examples
// MongoDB (Document) conceptual example
db.users.insertOne({
name: "Alice",
email: "alice@example.com",
preferences: { theme: "dark", lang: "en" }
});
// Redis (Key-Value) conceptual example
redis.set("user:123:session", "active_session_token");
Use Cases
- Big Data / Real-time Analytics: Handling massive streams of data.
- Content Management: Where documents have varying structures.
- Caching: Using Key-Value stores for ultra-low latency access to frequently used data.
- Social Networks: Using Graph databases to manage complex relationships.
Gotchas
- Lack of Standardized Query Language: Each NoSQL DB has its own API/query language.
- Eventual Consistency: Some NoSQL DBs trade immediate consistency for availability, meaning reads might return slightly stale data.
- Lack of Joins: Performing complex relationships across collections often requires manual work in the application code.
