Module 4B · NoSQL
The second part of syllabus Module 4 (the first part, distributed databases, is Module 4A). Why databases beyond the relational model appeared, the four NoSQL data models, and four real systems — MongoDB, Cassandra, HBase and Neo4j. To compare them fairly, every model stores the same CampusDB students, courses and enrollments you know from university_lab.
- ▸ Explain why NoSQL emerged, and the CAP theorem and BASE
- ▸ Model the same data as key-value, document, column-family and graph
- ▸ Run basic CRUD in MongoDB, Cassandra (CQL), HBase and Neo4j (Cypher)
- ▸ Describe how each system is deployed: replication, sharding, clusters
- ▸ Choose the right database for a workload, and name NoSQL’s challenges
The CampusDB data in every system. PostgreSQL examples use a scratch schema lab4b (CREATE SCHEMA lab4b;), removed at the end. For MongoDB, Cassandra, HBase and Neo4j, each section starts with how to run that system.
4.11 The Emergence of NoSQL
Why they appeared in the late 2000s:
- Web scale — Google, Amazon and Facebook needed to serve billions of requests over data that no single server could hold.
- Horizontal scaling — adding cheap machines (scale out) is easier than buying ever-bigger servers (scale up).
- Flexible schemas — new fields appear often in web and app data; changing a relational schema is slow at that scale.
- Always-on availability — keep working even when machines or links fail.
- The papers that started it — Google Bigtable (2006) and Amazon Dynamo (2007), followed by Cassandra (2008) and MongoDB (2009); the name “NoSQL” caught on in 2009. Non-relational databases are older — Module 2's hierarchical and network models — but the name and the boom are from this period.
The CAP theorem
| System | During a network partition it favours | Why |
|---|---|---|
| MongoDB | Consistency (CP) | Only the primary accepts writes; a cut-off minority has no primary |
| HBase | Consistency (CP) | Each row is served by exactly one RegionServer |
| Cassandra | Availability (AP) | Any replica accepts reads and writes; copies reconcile later |
| Neo4j cluster | Consistency (CP) | Writes go through an elected leader |
These are the defaults; most systems let you tune the trade-off per query (e.g. Cassandra's consistency levels in 4.16).
| ACID (relational) | BASE (many NoSQL systems) | |
|---|---|---|
| Stands for | Atomicity, Consistency, Isolation, Durability | Basically Available, Soft state, Eventually consistent |
| Priority | Correctness of every transaction | Availability and scale |
| After a write | Every reader sees it immediately | Replicas catch up over time (eventual consistency); a read may be stale for a moment |
| SQL (relational) | NoSQL | |
|---|---|---|
| Data model | Tables of rows and columns | Key-value, document, column-family or graph |
| Schema | Fixed, defined in advance | Flexible — each item may have different fields |
| Scaling | Mainly vertical (bigger server); horizontal is harder | Designed for horizontal scaling (sharding) |
| Relationships | Joins and foreign keys | Embedded data or application-side links (graphs are the exception) |
| Transactions | Full ACID | Often limited to one item; some (MongoDB, Neo4j) offer multi-document ACID |
| Query language | Standard SQL | Each system has its own (MQL, CQL, Cypher…) |
| Best for | Complex queries, strong consistency, structured data | Huge volumes, high write rates, changing structure, specific access patterns |
- ▸NoSQL = Not only SQL: non-relational models built for scale, flexibility and availability.
- ▸CAP: under a network partition, choose Consistency or Availability.
- ▸ACID = correctness first; BASE = availability first, eventually consistent.
4.12 Types of NoSQL Databases
key: student:2
value: {"name":"Diya Nair","dept":"DA", …}
→ the database sees only an opaque value, found by its key{ _id: 2, name: "Diya Nair", dept: "DA",
enrollments: [ { course: "CS201" },
{ course: "DA301" } ] }
→ the database understands the fields and can query themrow key: diya@duk.ac.in info: name=Diya Nair email=diya@duk.ac.in academic: dept=DA join_year=2024 → columns grouped into families; rows can differ
(:Student {name:"Diya Nair"})
-[:ENROLLED_IN]->(:Course {code:"CS201"})
-[:REQUIRES]->(:Course {code:"CS101"})
→ relationships are stored, not computed by joins| Model | Unit of data | Query by | Examples |
|---|---|---|---|
| Key-value | A value (any bytes) under a unique key | Key only | Redis, Memcached, Amazon DynamoDB, Oracle Coherence |
| Document | A self-describing document (JSON/BSON) with nested fields | Any field, including nested ones | MongoDB, CouchDB, Cloudant |
| Column-family | A row key with columns grouped into families; rows are sparse and can be very wide | Row key (and column ranges) | Cassandra, HBase, Google Bigtable, Accumulo |
| Graph | Nodes and relationships, both with properties | Pattern matching and traversals | Neo4j, Amazon Neptune, JanusGraph |
Filling a gap in the notes
The Module V lecture notes' list of types leaves out graph databases (Neo4j is in the syllabus) and calls the column-family group “tabular”. Cassandra belongs to the column-family group too.
- ▸Four families: key-value, document, column-family, graph.
- ▸Key-value hides the value’s structure; document databases understand it.
- ▸Column-family = sparse, wide rows in column families; graph = stored relationships.
4.13 Key-Value and Document Data Models
SET session:8f3a "diya@duk.ac.in" EX 1800 # a login session that expires in 30 minutes
GET session:8f3a # "diya@duk.ac.in"
INCR seats_taken:CS201:2024-Odd # atomic counter: (integer) 1, 2, 3 …
HSET student:2 name "Diya Nair" dept "DA" # a hash: several fields under one key
HGETALL student:2 # name, Diya Nair, dept, DAThere is no query like “all students in DA” — you must already know the key.
Designing documents: embed or reference?
| Embed (nest the data inside) | Reference (store an id, look it up) | |
|---|---|---|
| Example | A student document holds an enrollments array | An enrollment document holds student_id and course_id |
| Read | One read returns everything | Several reads, or a $lookup |
| Use when | Data is read together and the nested part stays small | The related data is large, shared, or changes independently |
| Relational equivalent | A pre-computed join (denormalized) | A foreign key |
Build one document per student from the relational tables — this is exactly what a MongoDB document would hold:
SELECT jsonb_pretty(jsonb_build_object(
'_id', s.student_id, 'name', s.full_name, 'email', s.email,
'join_year', s.join_year, 'dept', d.dept_code,
'enrollments', COALESCE((
SELECT jsonb_agg(jsonb_build_object('course', c.course_code, 'semester', sem.name)
ORDER BY c.course_code)
FROM inter.enrollments e
JOIN inter.course_offerings o ON o.offering_id = e.offering_id
JOIN inter.courses c ON c.course_id = o.course_id
JOIN inter.semesters sem ON sem.semester_id = o.semester_id
WHERE e.student_id = s.student_id), '[]'::jsonb)))
FROM inter.students s JOIN inter.departments d ON d.dept_id = s.dept_id
WHERE s.email = 'diya@duk.ac.in';
{
"_id": 2,
"dept": "DA",
"name": "Diya Nair",
"email": "diya@duk.ac.in",
"join_year": 2024,
"enrollments": [
{
"course": "CS201",
"semester": "2024-Odd"
},
{
"course": "DA301",
"semester": "2024-Odd"
}
]
}Store all six as a collection — a one-column table of documents:
CREATE TABLE lab4b.student_docs (doc JSONB NOT NULL);
INSERT INTO lab4b.student_docs (doc)
SELECT jsonb_build_object(
'name', s.full_name, 'email', s.email, 'join_year', s.join_year, 'dept', d.dept_code,
'enrollments', COALESCE((
SELECT jsonb_agg(jsonb_build_object('course', c.course_code, 'semester', sem.name)
ORDER BY c.course_code)
FROM inter.enrollments e
JOIN inter.course_offerings o ON o.offering_id = e.offering_id
JOIN inter.courses c ON c.course_id = o.course_id
JOIN inter.semesters sem ON sem.semester_id = o.semester_id
WHERE e.student_id = s.student_id), '[]'::jsonb))
FROM inter.students s JOIN inter.departments d ON d.dept_id = s.dept_id; -- INSERT 0 6Then query the documents:
-- documents that contain {"dept": "DA"}
SELECT doc->>'name' FROM lab4b.student_docs WHERE doc @> '{"dept": "DA"}';
-- Ananya Krishnan, Diya Nair
-- documents whose enrollments array contains a CS201 element
SELECT doc->>'name' FROM lab4b.student_docs
WHERE doc @> '{"enrollments": [{"course": "CS201"}]}';
-- Aarav Menon, Diya Nair, Kevin Thomas
-- flexible schema: give ONE document a new field
UPDATE lab4b.student_docs SET doc = doc || '{"phone": ["9847011111", "9847022222"]}'
WHERE doc->>'email' = 'fatima@duk.ac.in';
SELECT doc->>'name', doc->'phone' FROM lab4b.student_docs WHERE doc ? 'phone';
-- Fatima Rahman | ["9847011111", "9847022222"]
-- a GIN index makes containment queries fast on big collections
CREATE INDEX ON lab4b.student_docs USING GIN (doc);- ▸Key-value: get/put by key, value is opaque — fastest and simplest; no queries by content.
- ▸Document: self-describing JSON/BSON, flexible fields, query and index any field.
- ▸Embed what is read together; reference what is large, shared or changes on its own.
4.14 MongoDB — Use and Deployment
_id. It is queried with the MongoDB Query Language (MQL) from mongosh, the Compass GUI, or drivers for every programming language.| Relational | MongoDB |
|---|---|
| Database | Database |
| Table | Collection |
| Row | Document |
| Column | Field |
| Primary key | _id |
| Join | Embedding, or $lookup |
# MongoDB Community Server from mongodb.com, or with Docker:
docker run -d --name mongo -p 27017:27017 mongo:8
mongosh # the shell; connects to localhost:27017use campus
db.students.insertMany([
{ _id: 1, name: "Aarav Menon", email: "aarav@duk.ac.in", join_year: 2024, dept: "CS",
enrollments: [ { course: "CS101", semester: "2024-Odd" }, { course: "CS201", semester: "2024-Odd" } ] },
{ _id: 2, name: "Diya Nair", email: "diya@duk.ac.in", join_year: 2024, dept: "DA",
enrollments: [ { course: "CS201", semester: "2024-Odd" }, { course: "DA301", semester: "2024-Odd" } ] },
{ _id: 3, name: "Rohan Pillai", email: "rohan@duk.ac.in", join_year: 2023, dept: "CS", enrollments: [] },
{ _id: 4, name: "Fatima Rahman", email: "fatima@duk.ac.in", join_year: 2024, dept: "MA", enrollments: [] },
{ _id: 5, name: "Kevin Thomas", email: "kevin@duk.ac.in", join_year: 2023, dept: "CS",
enrollments: [ { course: "CS201", semester: "2024-Odd" } ] },
{ _id: 6, name: "Ananya Krishnan", email: "ananya@duk.ac.in", join_year: 2024, dept: "DA",
enrollments: [ { course: "DA301", semester: "2024-Odd" } ] }
])
// { acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5, '5': 6 } }db.students.find({ dept: "DA" }, { name: 1, _id: 0 })
// [ { name: 'Diya Nair' }, { name: 'Ananya Krishnan' } ]
db.students.find({ "enrollments.course": "CS201" }, { name: 1, _id: 0 }) // dot notation reaches inside arrays
// [ { name: 'Aarav Menon' }, { name: 'Diya Nair' }, { name: 'Kevin Thomas' } ]
db.students.find({ enrollments: { $size: 0 } }, { name: 1, _id: 0 }) // not enrolled anywhere
// [ { name: 'Rohan Pillai' }, { name: 'Fatima Rahman' } ]
db.students.countDocuments({ join_year: 2024 }) // 4db.students.aggregate([
{ $unwind: "$enrollments" }, // one document per enrollment
{ $group: { _id: "$enrollments.course", students: { $sum: 1 } } }, // count per course
{ $sort: { _id: 1 } }
])
// [ { _id: 'CS101', students: 1 }, { _id: 'CS201', students: 3 }, { _id: 'DA301', students: 2 } ]db.students.updateOne({ _id: 3 }, { $push: { enrollments: { course: "CS101", semester: "2024-Odd" } } })
// { acknowledged: true, matchedCount: 1, modifiedCount: 1, … } Rohan enrolls in CS101
db.students.updateOne({ _id: 4 }, { $set: { phone: ["9847011111", "9847022222"] } })
// only Fatima's document gains a phone field — no ALTER TABLE needed
db.students.deleteOne({ _id: 99 }) // { acknowledged: true, deletedCount: 0 }
db.students.createIndex({ email: 1 }, { unique: true }) // 'email_1' — like UNIQUE (email)Deployment
| Feature | How it works |
|---|---|
| Replica set | One primary takes all writes; secondaries copy its operation log. If the primary fails, the secondaries elect a new one automatically (failover, usually in seconds). Gives high availability. |
| Sharding | A collection is split by a shard key across shards (each a replica set). A mongos router sends each query to the right shards; config servers store which data lives where. Gives horizontal scaling. |
| Shard key choice | Ranged keys keep order but can create hot spots; hashed keys spread writes evenly but lose order. |
| Transactions | Single-document writes are atomic; multi-document ACID transactions exist since version 4.0. |
| Backup and tools | mongodump / mongorestore, file-system snapshots, and managed backups in MongoDB Atlas (cloud). Compass is the GUI. |
Corrections to the notes
The Module V lecture notes say MongoDB “has no approach for the backup of data in a consistent manner” and that GUI tools are not available — both are outdated: see the table above. It also defines sharding as preserving the order of the data; that is only true for ranged shard keys — hashed sharding deliberately scatters the order.
- ▸Database → collection → document (BSON) with a unique _id.
- ▸CRUD: insertMany / find / updateOne ($set, $push) / deleteOne; aggregate() is a pipeline of stages.
- ▸Replica set = availability (automatic failover). Sharding = scale-out by shard key, routed by mongos.
4.15 Column-Family Stores
| row key | family: info | family: academic | |||
|---|---|---|---|---|---|
| name | phone | dept | join_year | ||
| aarav@duk.ac.in | Aarav Menon | aarav@duk.ac.in | — not stored — | CS | 2024 |
| diya@duk.ac.in | Diya Nair | diya@duk.ac.in | 9847011111 | DA | 2024 |
| fatima@duk.ac.in | Fatima Rahman | fatima@duk.ac.in | — not stored — | MA | — not stored — |
| Relational row | Column-family row | |
|---|---|---|
| Columns | Fixed by the table definition; empty ones hold NULL | Each row stores only its own columns; new columns can be added at any time |
| Physical storage | Whole rows together | Each column family stored separately, sorted by row key |
| Access | Any column, any condition, joins | By row key (and ranges of keys); no joins |
| Strength | Flexible queries | Huge tables and very high write rates — logs, sensor data, messages, time series |
- ▸Row key → column families → columns; rows are sparse and can be very wide.
- ▸Data is spread and sorted by row key; queries should always use the key.
- ▸Bigtable’s design, used by HBase and (with its own twist) Cassandra.
4.16 Apache Cassandra — Use and Deployment
| Idea | Meaning |
|---|---|
| Ring (peer-to-peer) | Nodes form a ring; a hash of the partition key decides which node owns each row (consistent hashing). Nodes share their status by gossip. |
| Partition key | The first part of the PRIMARY KEY. All rows with the same partition key are stored together on the same nodes. |
| Clustering columns | The rest of the primary key. They sort the rows inside a partition. |
| Replication factor | How many nodes hold a copy of each partition (e.g. 3), set per keyspace — per data centre. |
| Tunable consistency | Each query chooses how many replicas must answer: ONE, QUORUM (a majority), ALL… |
| Query-first modeling | Design one table per query; duplicate the data rather than join. Queries must give the partition key. |
docker run -d --name cassandra -p 9042:9042 cassandra:5
# wait about a minute for the node to start, then:
docker exec -it cassandra cqlshThe query: attendance in one offering, newest class first. So the offering is the partition key and the class date sorts the rows.
CREATE KEYSPACE campus
WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}; -- 1 copy: a one-node lab
USE campus;
CREATE TABLE attendance_by_offering (
offering text, -- e.g. 'CS201-2024-Odd'
class_date date,
student text,
present boolean,
PRIMARY KEY ((offering), class_date, student) -- partition key, then clustering columns
) WITH CLUSTERING ORDER BY (class_date DESC, student ASC);
INSERT INTO attendance_by_offering (offering, class_date, student, present) VALUES ('CS201-2024-Odd', '2024-07-01', 'Aarav Menon', true);
INSERT INTO attendance_by_offering (offering, class_date, student, present) VALUES ('CS201-2024-Odd', '2024-07-01', 'Diya Nair', true);
INSERT INTO attendance_by_offering (offering, class_date, student, present) VALUES ('CS201-2024-Odd', '2024-07-01', 'Kevin Thomas', false);
INSERT INTO attendance_by_offering (offering, class_date, student, present) VALUES ('CS201-2024-Odd', '2024-07-02', 'Aarav Menon', true);SELECT class_date, student, present
FROM attendance_by_offering
WHERE offering = 'CS201-2024-Odd';
class_date | student | present
------------+--------------+---------
2024-07-02 | Aarav Menon | True
2024-07-01 | Aarav Menon | True
2024-07-01 | Diya Nair | True
2024-07-01 | Kevin Thomas | FalseSELECT * FROM attendance_by_offering WHERE student = 'Diya Nair';
InvalidRequest: Error from server: code=2200 [Invalid query] message="Cannot execute this query
as it might involve data filtering and thus may have unpredictable performance. If you want to
execute this query despite the performance unpredictability, use ALLOW FILTERING"
-- the Cassandra way: a second table, keyed for that query (the data is written twice)
CREATE TABLE attendance_by_student (
student text,
offering text,
class_date date,
present boolean,
PRIMARY KEY ((student), offering, class_date)
);CONSISTENCY QUORUM; -- Consistency level set to QUORUM. (a majority of replicas must answer)Note: an INSERT with an existing primary key silently overwrites the row (an “upsert”) — there is no duplicate-key error as in SQL.
Deployment
A production cluster has several nodes in one or more data centres, with NetworkTopologyStrategy and a replication factor of 3 per data centre. Because every node can take reads and writes, adding nodes adds capacity linearly, and a node or even a whole data centre can fail without downtime.
- ▸Masterless ring; the partition key’s hash picks the nodes; replication factor = number of copies.
- ▸PRIMARY KEY ((partition key), clustering columns): the partition key groups, clustering columns sort.
- ▸Design a table per query; always filter by the partition key; consistency is chosen per query.
4.17 Apache HBase — Use and Deployment
| Component | Role |
|---|---|
| HMaster | Assigns regions to RegionServers, handles table creation and schema changes |
| RegionServer | Serves reads and writes for its regions; writes go to a write-ahead log and an in-memory MemStore, later flushed to HFiles |
| Region | A range of row keys of one table; split automatically as it grows |
| ZooKeeper | Coordinates the cluster: tracks live servers and the active master |
| HDFS | Stores the HFiles and the WAL, replicated across DataNodes |
# HBase needs Java and runs on Linux (on Windows, use WSL).
# Standalone mode: download the binary release from hbase.apache.org, set JAVA_HOME, then:
bin/start-hbase.sh
bin/hbase shellcreate 'students', 'info', 'academic' # families are fixed; columns are not
put 'students', 'diya@duk.ac.in', 'info:name', 'Diya Nair'
put 'students', 'diya@duk.ac.in', 'academic:dept', 'DA'
put 'students', 'diya@duk.ac.in', 'academic:join_year', '2024'
put 'students', 'kevin@duk.ac.in', 'info:name', 'Kevin Thomas'
put 'students', 'kevin@duk.ac.in', 'academic:dept', 'CS'
get 'students', 'diya@duk.ac.in'
COLUMN CELL
academic:dept timestamp=…, value=DA
academic:join_year timestamp=…, value=2024
info:name timestamp=…, value=Diya Nair
1 row(s)
scan 'students' # every row, in row-key order
put 'students', 'diya@duk.ac.in', 'info:phone', '9847011111' # a new column, on the fly
count 'students' # 2 row(s)
disable 'students' # a table must be disabled before dropping
drop 'students'Values are stored as bytes — HBase has no data types; '2024' is just text. Old values of a cell are kept as earlier versions (how many is set per column family with VERSIONS).
| HBase | Cassandra | |
|---|---|---|
| Architecture | Master + RegionServers on HDFS | Masterless ring |
| Consistency | Strong (one server per row) — CP | Tunable, eventually consistent — AP |
| Query language | Shell / Java API (no SQL) | CQL (SQL-like) |
| Fits | Hadoop / big-data analytics pipelines | Always-on, write-heavy applications |
- ▸HBase = Bigtable on HDFS: HMaster, RegionServers, regions, ZooKeeper.
- ▸Shell: create, put, get, scan, count, disable, drop. Cells are untyped bytes with versions.
- ▸Strongly consistent per row; best inside the Hadoop ecosystem.
4.18 Neo4j and Graph Databases — Use and Deployment
:Student. Neo4j is the leading graph database and is queried with Cypher.In a relational database, connections are computed at query time by joins — the deeper the path, the more joins. A graph database stores each connection, so following one is a direct step, however large the database. That makes many-hop questions — prerequisite chains, friends of friends, recommendations, fraud rings — fast and simple to write.
docker run -d --name neo4j -p 7474:7474 -p 7687:7687 -e NEO4J_AUTH=neo4j/your-password neo4j:5
# then open Neo4j Browser at http://localhost:7474 (or use Neo4j Desktop, or the free AuraDB cloud)CREATE (cs101:Course {code: 'CS101', title: 'Introduction to Programming'}),
(cs210:Course {code: 'CS210', title: 'Data Structures'}),
(cs201:Course {code: 'CS201', title: 'Database Systems'}),
(da301:Course {code: 'DA301', title: 'Data Analytics'}),
(aarav:Student {name: 'Aarav Menon'}),
(diya:Student {name: 'Diya Nair'}),
(kevin:Student {name: 'Kevin Thomas'}),
(ananya:Student {name: 'Ananya Krishnan'}),
(cs201)-[:REQUIRES]->(cs101),
(cs201)-[:REQUIRES]->(cs210),
(da301)-[:REQUIRES]->(cs201),
(aarav)-[:ENROLLED_IN {semester: '2024-Odd'}]->(cs101),
(aarav)-[:ENROLLED_IN {semester: '2024-Odd'}]->(cs201),
(diya)-[:ENROLLED_IN {semester: '2024-Odd'}]->(cs201),
(diya)-[:ENROLLED_IN {semester: '2024-Odd'}]->(da301),
(kevin)-[:ENROLLED_IN {semester: '2024-Odd'}]->(cs201),
(ananya)-[:ENROLLED_IN {semester: '2024-Odd'}]->(da301);MATCH (s:Student)-[:ENROLLED_IN]->(:Course {code: 'CS201'})
RETURN s.name ORDER BY s.name;
// "Aarav Menon", "Diya Nair", "Kevin Thomas"MATCH path = (:Course {code: 'DA301'})-[:REQUIRES*]->(p:Course)
RETURN p.code AS prerequisite, length(path) AS level
ORDER BY level, prerequisite;
prerequisite | level
--------------+-------
"CS201" | 1
"CS101" | 2
"CS210" | 2
// the same answer as Module 3's WITH RECURSIVE query — in one line of pattern// classmates: students who share at least one course with Diya
MATCH (d:Student {name: 'Diya Nair'})-[:ENROLLED_IN]->(:Course)<-[:ENROLLED_IN]-(other:Student)
RETURN DISTINCT other.name ORDER BY other.name;
// "Aarav Menon", "Ananya Krishnan", "Kevin Thomas"
// courses her classmates take that she doesn't
MATCH (d:Student {name: 'Diya Nair'})-[:ENROLLED_IN]->(:Course)<-[:ENROLLED_IN]-(:Student)
-[:ENROLLED_IN]->(rec:Course)
WHERE NOT (d)-[:ENROLLED_IN]->(rec)
RETURN rec.code AS recommended, count(*) AS score ORDER BY score DESC;
// "CS101" | 1MATCH (s:Student {name: 'Kevin Thomas'}) SET s.phone = '9847033333';
MATCH (:Student {name: 'Kevin Thomas'})-[r:ENROLLED_IN]->(:Course {code: 'CS201'}) DELETE r;
MATCH (n) DETACH DELETE n; // empty the whole graph (removes relationships, then nodes)Deployment
Neo4j runs as a single server (Community or Enterprise edition), or as a cluster in which servers hold primary copies (they agree on every write through the Raft protocol, so writes stay consistent) and secondary copies that scale reads. Applications connect over the Bolt protocol (port 7687); the Browser uses port 7474. AuraDB is the managed cloud version.
- ▸Property graph: nodes (with labels) + directed relationships + properties on both.
- ▸Cypher patterns: (a)-[:REL]->(b); variable length: -[:REL*]->; MATCH … WHERE … RETURN.
- ▸Graphs shine for many-hop questions: paths, networks, recommendations, fraud.
4.19 Applications and Challenges of NoSQL
| Need | Good fit | A university example |
|---|---|---|
| Very fast look-ups by key, caching, sessions, counters | Key-value (Redis) | Login sessions; live seat counters during registration week |
| Varied, nested records that change shape | Document (MongoDB) | Student portfolios with projects, certificates and publications |
| Huge write volumes, time series, logs | Column-family (Cassandra, HBase) | Wi-Fi and attendance logs from every classroom |
| Highly connected data, many-hop questions | Graph (Neo4j) | Prerequisite chains; course recommendations; research collaborations |
| Transactions, integrity, complex reporting | Relational (PostgreSQL) | Admissions, fees, marks and transcripts |
Large systems often combine several databases, each for what it does best — polyglot persistence. A university portal might keep transcripts in PostgreSQL, sessions in Redis and course recommendations in Neo4j.
| Advantages | Challenges |
|---|---|
| High scalability — scale out by sharding across cheap machines | Weaker consistency — eventual consistency allows stale reads; multi-item transactions are limited in many systems |
| High availability — automatic replication and failover | No joins in most systems — data is duplicated, and the application must keep the copies in step |
| Flexible schema — add fields without migrations | No standard query language — MQL, CQL, Cypher… each must be learned |
| Fast for the access pattern it was designed for | Ad-hoc questions the design did not plan for can be slow or impossible |
| Natural fit for JSON apps, logs and networks | Modeling skills, operations and tooling are less mature than for relational databases |
Updating the notes' list of disadvantages
“Open source” is not a disadvantage (PostgreSQL is open source too, and some NoSQL systems are commercial) — the real issue is the lack of a common standard. Today's NoSQL systems do have GUIs (Compass, Neo4j Browser) and consistent backup tools, and the size cost of descriptive field names is reduced by compression.
- ▸Choose by access pattern: key-value (look-ups), document (flexible records), column-family (huge writes), graph (connections), relational (transactions and reporting).
- ▸Polyglot persistence: use several databases together.
- ▸Main challenges: consistency, no joins, no standard language, less flexible querying.
Tidy up after the lab
# PostgreSQL (in psql, connected to university_lab)
DROP SCHEMA lab4b CASCADE;
# NoSQL containers, if you used Docker
docker rm -f mongo cassandra neo4jModule 4B at a glance
| Topic | One-line answer |
|---|---|
| NoSQL | Non-relational models for scale, flexibility and availability (Not only SQL). |
| CAP / BASE | Under a partition choose C or A; BASE = basically available, soft state, eventually consistent. |
| Models | Key-value, document, column-family, graph. |
| MongoDB | Documents in collections; MQL CRUD and aggregation; replica sets and sharding. |
| Column-family | Row key → column families → sparse, wide rows (Bigtable design). |
| Cassandra | Masterless ring, partition + clustering keys, query-first tables, tunable consistency. |
| HBase | Bigtable on HDFS: HMaster, RegionServers, regions; strongly consistent per row. |
| Neo4j | Property graph queried with Cypher; stored relationships make many-hop queries fast. |
| Choosing | By access pattern; often several together (polyglot persistence). |
Practice
Pick the model
EasyQuery documents in PostgreSQL
MediumA MongoDB filter
MediumModel a Cassandra table for a query
MediumWalk the graph the other way
HardExam-style questions
- What does NoSQL stand for? Why did it emerge?
- State the CAP theorem.
- Differentiate ACID and BASE.
- What is a partition key in Cassandra?
- What is a column family?
- What is a property graph?
- Explain the four NoSQL data models with examples.
- Compare SQL and NoSQL databases.
- Explain MongoDB’s data model, CRUD operations and deployment (replica sets, sharding).
- Explain Cassandra’s architecture and data modeling.
- Explain HBase architecture.
- Explain graph databases and Cypher with examples.
