Digital University Kerala

SQL Lab Notes

PostgreSQL for Data Analytics

Course Instructor:Dr. Ajith Kumar
Academic Year: 2026-2028
Class Notes/Module 4B
Module 4B · CO4 · Lecture notes: Module V · Labs 8, 9

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.

🎯 After this module you can
  • ▸ 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
🏫 Examples use

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.

Set up university_lab first →

4.11 The Emergence of NoSQL

📖 Definition · NoSQL
“Not only SQL” — databases that store data in models other than relational tables: key-value pairs, documents, column families or graphs. They are designed for very large data, flexible structure and horizontal scaling across many machines.

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

📖 Definition · CAP theorem (Brewer, 2000)
A distributed database can guarantee at most two of: Consistency (every read sees the latest write), Availability (every request gets a response) and Partition tolerance (it keeps working when the network splits). Since network partitions do happen, the real choice during a partition is between C and A.
SystemDuring a network partition it favoursWhy
MongoDBConsistency (CP)Only the primary accepts writes; a cut-off minority has no primary
HBaseConsistency (CP)Each row is served by exactly one RegionServer
CassandraAvailability (AP)Any replica accepts reads and writes; copies reconcile later
Neo4j clusterConsistency (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 forAtomicity, Consistency, Isolation, DurabilityBasically Available, Soft state, Eventually consistent
PriorityCorrectness of every transactionAvailability and scale
After a writeEvery reader sees it immediatelyReplicas catch up over time (eventual consistency); a read may be stale for a moment
SQL (relational)NoSQL
Data modelTables of rows and columnsKey-value, document, column-family or graph
SchemaFixed, defined in advanceFlexible — each item may have different fields
ScalingMainly vertical (bigger server); horizontal is harderDesigned for horizontal scaling (sharding)
RelationshipsJoins and foreign keysEmbedded data or application-side links (graphs are the exception)
TransactionsFull ACIDOften limited to one item; some (MongoDB, Neo4j) offer multi-document ACID
Query languageStandard SQLEach system has its own (MQL, CQL, Cypher…)
Best forComplex queries, strong consistency, structured dataHuge volumes, high write rates, changing structure, specific access patterns
✅ Remember
  • ▸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

📖 Definition
NoSQL systems fall into four families by data model: key-value, document, column-family (wide-column) and graph.
Key-value (Redis)
key:   student:2
value: {"name":"Diya Nair","dept":"DA", …}
→ the database sees only an opaque value, found by its key
Document (MongoDB)
{ _id: 2, name: "Diya Nair", dept: "DA",
  enrollments: [ { course: "CS201" },
                 { course: "DA301" } ] }
→ the database understands the fields and can query them
Column-family (Cassandra, HBase)
row 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
Graph (Neo4j)
(:Student {name:"Diya Nair"})
   -[:ENROLLED_IN]->(:Course {code:"CS201"})
   -[:REQUIRES]->(:Course {code:"CS101"})
→ relationships are stored, not computed by joins
Figure 4.6 — Diya Nair stored in each of the four NoSQL models
ModelUnit of dataQuery byExamples
Key-valueA value (any bytes) under a unique keyKey onlyRedis, Memcached, Amazon DynamoDB, Oracle Coherence
DocumentA self-describing document (JSON/BSON) with nested fieldsAny field, including nested onesMongoDB, CouchDB, Cloudant
Column-familyA row key with columns grouped into families; rows are sparse and can be very wideRow key (and column ranges)Cassandra, HBase, Google Bigtable, Accumulo
GraphNodes and relationships, both with propertiesPattern matching and traversalsNeo4j, 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.

✅ Remember
  • ▸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

📖 Definition · Key-value model
The simplest model: a giant dictionary. Each item is a unique key and a value the database does not look inside. Operations are put, get and delete by key — extremely fast and easy to spread across machines.
📖 Definition · Document model
Each item is a document — usually JSON or BSON — with named, nested fields. Documents in one collection need not have the same fields, and the database can query and index any field.
🏫 Example · key-value in Redis — sessions and counters
redis-clibash
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, DA

There 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)
ExampleA student document holds an enrollments arrayAn enrollment document holds student_id and course_id
ReadOne read returns everythingSeveral reads, or a $lookup
Use whenData is read together and the nested part stays smallThe related data is large, shared, or changes independently
Relational equivalentA pre-computed join (denormalized)A foreign key
🏫 Example · PostgreSQL can store documents too (JSONB)

Build one document per student from the relational tables — this is exactly what a MongoDB document would hold:

Relational rows → a JSON document (Diya)sql
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:

A document collection in PostgreSQLsql
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 6

Then query the documents:

Querying documents: containment (@>), nested arrays, a new fieldsql
-- 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);
✅ Remember
  • ▸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

📖 Definition
MongoDB is the most widely used document database. It stores BSON (binary JSON) documents in collections inside databases; every document has a unique _id. It is queried with the MongoDB Query Language (MQL) from mongosh, the Compass GUI, or drivers for every programming language.
RelationalMongoDB
DatabaseDatabase
TableCollection
RowDocument
ColumnField
Primary key_id
JoinEmbedding, or $lookup
Run it (Lab 8)bash
# 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:27017
🏫 Example · CRUD on the CampusDB students
Create — six student documents with embedded enrollmentsjavascript
use 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 } }
Read — filter, project, query inside arrays, countjavascript
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 })                             // 4
Aggregation pipeline — students per course (like GROUP BY)javascript
db.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 } ]
Update, delete, and an indexjavascript
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

FeatureHow it works
Replica setOne 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.
ShardingA 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 choiceRanged keys keep order but can create hot spots; hashed keys spread writes evenly but lose order.
TransactionsSingle-document writes are atomic; multi-document ACID transactions exist since version 4.0.
Backup and toolsmongodump / 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.

✅ Remember
  • ▸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

📖 Definition
A column-family (wide-column) store keeps each row under a row key, with its columns grouped into column families. Rows are sparse — a row stores only the columns it has — and can be very wide. Data is distributed across machines by row key. The design comes from Google's Bigtable paper (2006).
row keyfamily: infofamily: academic
nameemailphonedeptjoin_year
aarav@duk.ac.inAarav Menonaarav@duk.ac.in— not stored —CS2024
diya@duk.ac.inDiya Nairdiya@duk.ac.in9847011111DA2024
fatima@duk.ac.inFatima Rahmanfatima@duk.ac.in— not stored —MA— not stored —
Figure 4.7 — The students table as a column-family store: sparse rows, columns grouped into families
Relational rowColumn-family row
ColumnsFixed by the table definition; empty ones hold NULLEach row stores only its own columns; new columns can be added at any time
Physical storageWhole rows togetherEach column family stored separately, sorted by row key
AccessAny column, any condition, joinsBy row key (and ranges of keys); no joins
StrengthFlexible queriesHuge tables and very high write rates — logs, sensor data, messages, time series
✅ Remember
  • ▸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

📖 Definition
Cassandra is a distributed wide-column database built for high write rates and continuous availability. Every node is equal — there is no master. Data lives in keyspaces (like a database) and tables, and is queried with CQL, a SQL-like language.
IdeaMeaning
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 keyThe first part of the PRIMARY KEY. All rows with the same partition key are stored together on the same nodes.
Clustering columnsThe rest of the primary key. They sort the rows inside a partition.
Replication factorHow many nodes hold a copy of each partition (e.g. 3), set per keyspace — per data centre.
Tunable consistencyEach query chooses how many replicas must answer: ONE, QUORUM (a majority), ALL…
Query-first modelingDesign one table per query; duplicate the data rather than join. Queries must give the partition key.
Run it (Lab 8)bash
docker run -d --name cassandra -p 9042:9042 cassandra:5
# wait about a minute for the node to start, then:
docker exec -it cassandra cqlsh
🏫 Example · attendance, modeled for its query

The query: attendance in one offering, newest class first. So the offering is the partition key and the class date sorts the rows.

CQL — keyspace, table, insertssql
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);
Read by partition key — rows come back in clustering ordersql
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 |   False
Without the partition key, Cassandra refuses (it would have to search every node)sql
SELECT * 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)
);
Tunable consistency in cqlshsql
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.

✅ Remember
  • ▸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

📖 Definition
HBase is the open-source Bigtable for the Hadoop ecosystem: a column-family store that keeps its data in HDFS (the Hadoop Distributed File System). Tables are split by row-key range into regions, served by RegionServers. Every cell is versioned by timestamp.
ComponentRole
HMasterAssigns regions to RegionServers, handles table creation and schema changes
RegionServerServes reads and writes for its regions; writes go to a write-ahead log and an in-memory MemStore, later flushed to HFiles
RegionA range of row keys of one table; split automatically as it grows
ZooKeeperCoordinates the cluster: tracks live servers and the active master
HDFSStores the HFiles and the WAL, replicated across DataNodes
Run it (Lab 8)bash
# 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 shell
🏫 Example · students in the HBase shell
Create a table with two column families, then put, get and scanruby
create '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).

HBaseCassandra
ArchitectureMaster + RegionServers on HDFSMasterless ring
ConsistencyStrong (one server per row) — CPTunable, eventually consistent — AP
Query languageShell / Java API (no SQL)CQL (SQL-like)
FitsHadoop / big-data analytics pipelinesAlways-on, write-heavy applications
✅ Remember
  • ▸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

📖 Definition · Property graph
Data stored as nodes (things), relationships (directed, named connections between nodes) and properties (key-value pairs on both). Nodes carry labels such as :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.

AaravDiyaKevinAnanyaCS101CS201CS210DA301:Student:Course
Figure 4.8 — CampusDB as a property graph (grey: ENROLLED_IN, red: REQUIRES)
Run it (Lab 9)bash
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)
🏫 Example · CampusDB in Cypher
Create nodes and relationships in one statementcypher
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 a pattern — who is enrolled in CS201?cypher
MATCH (s:Student)-[:ENROLLED_IN]->(:Course {code: 'CS201'})
RETURN s.name ORDER BY s.name;
// "Aarav Menon", "Diya Nair", "Kevin Thomas"
Variable-length path — every prerequisite of DA301, at any depthcypher
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
Two hops — Diya’s classmates, and a course recommendationcypher
// 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" | 1
Update and deletecypher
MATCH (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.

✅ Remember
  • ▸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

📖 Definition
No one database is best for everything. NoSQL systems win for specific access patterns at large scale; relational systems win when data is highly connected, must be strongly consistent, or is queried in many different ways.
NeedGood fitA university example
Very fast look-ups by key, caching, sessions, countersKey-value (Redis)Login sessions; live seat counters during registration week
Varied, nested records that change shapeDocument (MongoDB)Student portfolios with projects, certificates and publications
Huge write volumes, time series, logsColumn-family (Cassandra, HBase)Wi-Fi and attendance logs from every classroom
Highly connected data, many-hop questionsGraph (Neo4j)Prerequisite chains; course recommendations; research collaborations
Transactions, integrity, complex reportingRelational (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.

AdvantagesChallenges
High scalability — scale out by sharding across cheap machinesWeaker consistency — eventual consistency allows stale reads; multi-item transactions are limited in many systems
High availability — automatic replication and failoverNo joins in most systems — data is duplicated, and the application must keep the copies in step
Flexible schema — add fields without migrationsNo standard query language — MQL, CQL, Cypher… each must be learned
Fast for the access pattern it was designed forAd-hoc questions the design did not plan for can be slow or impossible
Natural fit for JSON apps, logs and networksModeling 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.

✅ Remember
  • ▸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

Remove what this module createdbash
# PostgreSQL (in psql, connected to university_lab)
DROP SCHEMA lab4b CASCADE;

# NoSQL containers, if you used Docker
docker rm -f mongo cassandra neo4j

Module 4B at a glance

TopicOne-line answer
NoSQLNon-relational models for scale, flexibility and availability (Not only SQL).
CAP / BASEUnder a partition choose C or A; BASE = basically available, soft state, eventually consistent.
ModelsKey-value, document, column-family, graph.
MongoDBDocuments in collections; MQL CRUD and aggregation; replica sets and sharding.
Column-familyRow key → column families → sparse, wide rows (Bigtable design).
CassandraMasterless ring, partition + clustering keys, query-first tables, tunable consistency.
HBaseBigtable on HDFS: HMaster, RegionServers, regions; strongly consistent per row.
Neo4jProperty graph queried with Cypher; stored relationships make many-hop queries fast.
ChoosingBy access pattern; often several together (polyglot persistence).

Practice

1

Pick the model

Easy
Which NoSQL model fits each need? (a) storing the shopping-cart of each logged-in user; (b) a library catalogue where books, theses and videos have different fields; (c) 10 million sensor readings per day; (d) 'who co-authored with someone who co-authored with Dr. Nisha?'
2

Query documents in PostgreSQL

Medium
Using lab4b.student_docs from 4.13, list the students whose enrollments array is empty.
3

A MongoDB filter

Medium
In the campus database, find the names of Computer Science students who joined in 2023.
4

Model a Cassandra table for a query

Medium
Design a Cassandra table that answers: 'all the classes a student attended in one semester, newest first'.
5

Walk the graph the other way

Hard
Write a Cypher query that lists every course that requires CS101, directly or indirectly.

Exam-style questions

Short answer (2 marks)
  1. What does NoSQL stand for? Why did it emerge?
  2. State the CAP theorem.
  3. Differentiate ACID and BASE.
  4. What is a partition key in Cassandra?
  5. What is a column family?
  6. What is a property graph?
Long answer (5–10 marks)
  1. Explain the four NoSQL data models with examples.
  2. Compare SQL and NoSQL databases.
  3. Explain MongoDB’s data model, CRUD operations and deployment (replica sets, sharding).
  4. Explain Cassandra’s architecture and data modeling.
  5. Explain HBase architecture.
  6. Explain graph databases and Cypher with examples.