0% found this document useful (0 votes)
5 views17 pages

LAB RECORD NoSql

The document outlines various exercises aimed at teaching students how to implement CRUD operations and manage data using NoSQL databases such as Redis, Cassandra, MongoDB, and Neo4J. It includes practical programming tasks using Node.js and Express, installation procedures for each database, and examples of performing basic queries and data handling. Additionally, it covers the concepts of data modeling, sharding, and replication in NoSQL environments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views17 pages

LAB RECORD NoSql

The document outlines various exercises aimed at teaching students how to implement CRUD operations and manage data using NoSQL databases such as Redis, Cassandra, MongoDB, and Neo4J. It includes practical programming tasks using Node.js and Express, installation procedures for each database, and examples of performing basic queries and data handling. Additionally, it covers the concepts of data modeling, sharding, and replication in NoSQL environments.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Course Outcomes:

At the end of the lab, student will be able to


● Implement CRUD operations on various NoSQL databases.
● Implement the concepts of sharding and replication over popular NoSQL Databases
● Implement the concepts of NoSQL databases using databases that include
MongoDB for document databases, Cassandra for columnfamily databases, and
Neo4J for graph databases.
● Implement various data modeling techniques and understand the characteristics of
NoSQL databases.

Exercise - 1: Write a program to insert student details using Redis


and NodejS/Express

require("dotenv").config();
const express = require("express");
const redis = require("redis");
const bodyParser = require("body-parser");

const app = express();


app.use(bodyParser.json());

// Connect to Redis
const redisClient = redis.createClient({
url: process.env.REDIS_URL || "redis://localhost:6379",
});
redisClient.connect()
.then(() => console.log("Connected to Redis"))
.catch((err) => console.log("Redis Connection Error:", err));

app.post("/students", async (req, res) => {


try {
const { rollNumber, name, class: studentClass, email, phone } = req.body;

if (!rollNumber) return res.status(400).json({ error: "Roll Number is required" });

const studentData = JSON.stringify({ name, studentClass, email, phone });


await redisClient.set(`student:${rollNumber}`, studentData);

res.status(201).json({ message: "Student added successfully!" });


} catch (err) {
res.status(500).json({ error: err.message });
}
});

app.get("/students/:rollNumber", async (req, res) => {


try {
const rollNumber = req.params.rollNumber;
const student = await redisClient.get(`student:${rollNumber}`);

if (!student) return res.status(404).json({ message: "Student not found" });

res.json(JSON.parse(student));
} catch (err) {
res.status(500).json({ error: err.message });
}
});

const PORT = process.env.PORT || 5000;


app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Output

1. POST /students
• Input (Request Body): When you send a POST request to /students with the following
JSON body (for example):
json
CopyEdit
{
"rollNumber": "101",
"name": "John Doe",
"class": "10th Grade",
"email": "[email protected]",
"phone": "1234567890"
}
• Process:
o The server checks if the rollNumber is provided. If it is, it proceeds to save the
student data.
o The student details are stored in Redis under the key student:101.
• Output: If the request is successful, the server will respond with:
json
CopyEdit
{
"message": "Student added successfully!"
}
• If the rollNumber is missing in the request body, it will respond with an error:
json
CopyEdit
{
"error": "Roll Number is required"
}
2. GET /students/:rollNumber
• Input (Request): When you send a GET request to /students/101 (assuming you have
already added a student with roll number 101 using the POST endpoint), the server will
fetch the data stored in Redis.
• Process:
o The server will try to get the student data using the key student:101.
o If the student data exists, it will return the details in JSON format.
• Output: The response will be:
json
CopyEdit
{
"name": "John Doe",
"studentClass": "10th Grade",
"email": "[email protected]",
"phone": "1234567890"
}
• If no student is found for the given rollNumber, it will return:
json
CopyEdit
{
"message": "Student not found"
}
3. Error Handling
• If there's any error while connecting to Redis or during the execution of any operation,
such as an invalid request or server failure, the server will respond with a 500 status
code and the corresponding error message.
Example of running the program:
1. Start the server with node <your_file_name.js>.
2. Make a POST request to add student details:
o Using tools like Postman or curl:
bash
CopyEdit
curl -X POST http://localhost:5000/students -H "Content-Type: application/json" -d
'{"rollNumber": "101", "name": "John Doe", "class": "10th Grade", "email":
"[email protected]", "phone": "1234567890"}'
o You will get:
json
CopyEdit
{
"message": "Student added successfully!"
}
3. Make a GET request to retrieve student details:
bash
CopyEdit
curl http://localhost:5000/students/101
o You will get:
json
CopyEdit
{
"name": "John Doe",
"studentClass": "10th Grade",
"email": "[email protected]",
"phone": "1234567890"
}
If there is an issue connecting to Redis or any error occurs in the code, you'll get a 500 error
response with the respective message.

Exercise - 2 : Procedure to install Cassandra in Ubuntu


Environment
Aim: To install Casandra on Ubuntu Environment.

What Is Apache Cassandra

Apache Cassandra is an open-source database management system that runs on Not Only
SQL model and uses a partitioned wide column storage data model. It mainly focuses on speed,
scalability, and performance.

Step 1. Download and Install Java

First, access your VPS via SSH and determine if you have Java installed.

java -version

Step 2. Add the GPG Key

sudo apt install wget


wget -q -O - https://www.apache.org/dist/cassandra/KEYS | sudo apt-key add
-

Step 3. Add the Cassandra Repository File

echo "deb http://www.apache.org/dist/cassandra/debian 40x main" | sudo tee


-a /etc/apt/sources.list.d/cassandra.sources.list deb
http://www.apache.org/dist/cassandra/debian 40x main

Step 4. Install Cassandra on Ubuntu

sudo apt-get update


sudo apt install cassandra -y

Step 5. Enable and Start Cassandra

sudo systemctl enable cassandra


sudo systemctl start cassandra

Step 6. Verify the Installation

sudo systemctl status cassandra

Exercise -3 : Perform Basic Cassandra Query Language


(CQL) Commands
Aim: To perform Basic Cassandra Query Language (CQL) Commands

Cqlsh

cqlsh, or Cassandra query language shell, is used to communicate with Cassandra and initiate
Cassandra Query Language. To start cqlsh, use the following command/

root@myawesomevps:/# cqlsh

CREATE KEYSPACE:

A keyspace specifies data replication. In the following example, we will create a new keyspace
and specify the replication factor:
cqlsh> CREATE KEYSPACE testingout
WITH REPLICATION = {
'class' : 'SimpleStrategy',
'replication_factor' : 1
};

SHOW
The SHOW command displays all the information about the current cqlsh session. You can
choose between showing host, version, and session information:

cqlsh> SHOW VERSION


[cqlsh 6.0.0 | Cassandra 4.0.5 | CQL spec 3.4.5 | Native protocol v5]

cqlsh> SHOW HOST


Connected to Test Cluster at 127.0.0.1:9042

USE
The USE command sets the current working keyspace:

cqlsh> USE testingout;

CREATE TABLE

In order to create a table, users need to use the CREATE TABLE command.

cqlsh:testingout> CREATE TABLE tabletest (


name TEXT PRIMARY KEY,
surname TEXT,
phone INT );
INSERT
INSERT command is used to add an entire row into a table. Mind that missing values will be set
to null:

cqlsh:testingout>
INSERT INTO tabletest (name, surname, phone)
VALUES ('John', 'Johnson', 456123789);

Exercise - 4 : Procedure to install MONGODB in Ubuntu


Environment
Aim: To install MongoDB on Ubuntu Environment.

Procedure:
To install MongoDB in an Ubuntu environment, you can follow these steps:

Step 1: Import the MongoDB GPG Key

wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-


key add -

Step 2: Create a MongoDB Repository File

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu


$(lsb_release -sc)/mongodb-org/5.0 multiverse" | sudo tee
/etc/apt/sources.list.d/mongodb-org-5.0.list

Step 3: Update the Packages

sudo apt update

Step 4: Install MongoDB

sudo apt install -y mongodb-org

Step 5: Start MongoDB

sudo systemctl start mongod

Exercise- 5: Perform CRUD Operation using MongoDB


db.student.insert({
regNo: "3014",
name: "Test Student",
course: {
courseName: "MCA",
duration: "3 Years"
},
address: {
city: "Bangalore",
state: "KA",
country: "India"
}
})
MongoDB: Querying a document from a collection(Read)

db.student.find()

To find specific value: db.collection_name.find({"fieldname":"value"})

db.students.find({"regNo":"3014"})

MongoDB: Updating a document in a collection(Update)

db.student.update({
"regNo": "3014"
},
$set:
{
"name":"Viraj"
})

MongoDB: Removing an entry from the collection(Delete)

db.collection_name.remove({"fieldname":"value"})

db.collection_name.remove({"regno":"3014"})

Exercise - 6: Program to create a TO-DO List with NodeJS,


Express and MongoDB, EJS
INDEX.HTML file

<html>
<head>
<title>Add tasks</title>
</head>
<body>
<form method="post" action="/">
<input name = "inputvalue" type = "text" placeholder="Enter a task"> <button> Submit</button>
<button id="view"> <a href="/tasks"> View Tasks </a></button> </form>
</body>
</html>
INDEX.JS file

const express = require('express');


const bodyParser = require("body-parser");
const app = express()
const ejs = require('ejs');
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }))
const MongoClient = require("mongodb").MongoClient;
const uri =
"mongodb+srv://sumukhremala:[email protected]/MyDataBase"
const client = new MongoClient(uri, { useNewUrlParser: true }); client.connect((err) => {
if (err) throw err
});
const collection = client.db("MyDataBase").collection("MyCollection"); app.post("/", function(req,
res) {
let newTask = req.body.inputvalue
collection.insertOne({ task: newTask }, function(err, result) { if (err) throw err
});
console.log("New task inserted successfully");
})
app.get("/tasks", function(req, res) {
collection.find().toArray()
.then(function(tasks) {
console.log(tasks)
res.render('tasks', { tasks: tasks });
})
});
app.get("/", function(req, res) {
res.sendFile(__dirname + '/index.html');
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});

TASKS.EJS file
<!DOCTYPE html>
<html>
<head>
<title>My Array</title>
</head>
<body>
<h1>Your To-Do List</h1>
<ul>
<% tasks.forEach(function(item) { %>
<li><%= item.task %></li>
<% }); %>
</ul>
</body>
</html>

Exercise - 7: Build an application that can store student details


and retrieve them by using their ‘Roll Number’

require("dotenv").config();
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");

const app = express();


app.use(bodyParser.json());

// MongoDB Connection
mongoose
.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("MongoDB Connected"))
.catch((err) => console.log("DB Connection Error:", err));

// Student Schema
const studentSchema = new mongoose.Schema({
name: String,
rollNumber: { type: String, unique: true, required: true },
class: String,
email: String,
phone: String,
});

const Student = mongoose.model("Student", studentSchema);

// Routes

// Add Student
app.post("/students", async (req, res) => {
try {
const student = new Student(req.body);
await student.save();
res.status(201).json({ message: "Student added successfully!", student });
} catch (err) {
res.status(400).json({ error: err.message });
}
});

// Get Student by Roll Number


app.get("/students/:rollNumber", async (req, res) => {
try {
const student = await Student.findOne({ rollNumber: req.params.rollNumber });
if (!student) return res.status(404).json({ message: "Student not found" });
res.json(student);
} catch (err) {
res.status(500).json({ error: err.message });
}
});

// Get All Students


app.get("/students", async (req, res) => {
try {
const students = await Student.find();
res.json(students);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Exercise - 8: Explain about Graph Databases in detail. Write a


procedure to install Neo4J on Ubuntu Environment.
What is a Graph Database?
A graph is a pictorial representation of a set of objects where some pairs of objects are
connected by links. It is composed of two elements - nodes (vertices) and relationships (edges).

Graph database is a database used to model the data in the form of graph. In here, the nodes of
a graph depict the entities while the relationships depict the association of these nodes.

To install Neo4j on Ubuntu, you can follow these steps:

Step 1: Import the Neo4j GPG Key

wget -O - https://debian.neo4j.com/neotechnology.gpg.key | sudo apt-key add -

Step 2: Add the Neo4j Repository

echo 'deb https://debian.neo4j.com stable 4.3' | sudo tee /etc/apt/sources.list.d/neo4j.list

Step 3: Update the Packages

sudo apt update

Step 4: Install Neo4j

sudo apt install neo4j

Step 5: Start Neo4j

sudo systemctl start neo4j

By default, Neo4j will be accessible on http://localhost:7474. You can access the Neo4j browser
by opening that URL in a web browser.
During the installation process, you'll be prompted to set up a password for the neo4j user. You
can check the status of the Neo4j service using the following command:

sudo systemctl status neo4j

Use Case: A Retail Recommendation Engine Using Neo4j

The graph shows how we use a simple linked list of shopping baskets connected by NEXT
relationships to create a purchase history for the customer.

Explanation:

In the graph above, we see that the customer has visited three times, saved their first purchase
for later (the SAVED relationship between customer and basket nodes).
Ultimately, the customer bought one basket (indicated by the BOUGHT relationship between
customer and basket node) and is currently assembling a basket, shown by the CURRENT
relationship that points to an active basket at the head of the linked list.

Conclusion: In graph form, it’s easy to figure out the customer’s behavior: They became a
(potential) new customer but failed to commit to buying toothpaste and came back one day later
and bought toothpaste, bread and butter. Finally, the customer settled on buying bread and
butter in their next purchase – which is a repeated pattern in their purchase history we could
ultimately use to serve them better.

Exercise -9: Create four students network Node A, Node B,


Node C, Node D with their own properties (name, roll
number, phone, email),

B) Mark their relationship as friend and retrieve the


relationship using Neo4J

CREATE (A:Student {name: "Alice", roll_no: "101", phone: "9876543210", email:


"[email protected]"})
CREATE (B:Student {name: "Bob", roll_no: "102", phone: "9876543211", email:
"[email protected]"})
CREATE (C:Student {name: "Charlie", roll_no: "103", phone: "9876543212", email:
"[email protected]"})
CREATE (D:Student {name: "David", roll_no: "104", phone: "9876543213", email:
"[email protected]"});

Creating Relationship

MATCH (A:Student {name: "Alice"}), (B:Student {name: "Bob"})


CREATE (A)-[:FRIEND]->(B), (B)-[:FRIEND]->(A);
MATCH (B:Student {name: "Bob"}), (C:Student {name: "Charlie"})
CREATE (B)-[:FRIEND]->(C), (C)-[:FRIEND]->(B);
MATCH (C:Student {name: "Charlie"}), (D:Student {name: "David"})
CREATE (C)-[:FRIEND]->(D), (D)-[:FRIEND]->(C);
MATCH (D:Student {name: "David"}), (A:Student {name: "Alice"})
CREATE (D)-[:FRIEND]->(A), (A)-[:FRIEND]->(D);
Retrieve Relationship
MATCH (s:Student)-[:FRIEND]->(f:Student)
RETURN s.name AS Student, f.name AS Friend;

A) Create a group of four friends, mark their relationship as friends and then
create another node name "Vishnu institute of technology" join these people as
"students" in Vishnu institute of technology.

B) Create 3 different hobbies connected to those friends, mark them as hobbies


of theirs. One of the hobbies of these must match with another person

C) View the student, Has_Hobby and Friends relation

D) View all nodes and relationships

E) Change the music hobby to 'Movies'

F) Delete the Bob, Gaming nodes and the relationship from the database and print
the final nodes and relationships

A) Create Friends and Connect Them to Vishnu Institute of Technology


CREATE (A:Student {name: "Alice", roll_no: "101", phone: "9876543210", email:
"[email protected]"}),
(B:Student {name: "Bob", roll_no: "102", phone: "9876543211", email:
"[email protected]"}),
(C:Student {name: "Charlie", roll_no: "103", phone: "9876543212", email:
"[email protected]"}),
(D:Student {name: "David", roll_no: "104", phone: "9876543213", email:
"[email protected]"}),
(VIT:Institution {name: "Vishnu Institute of Technology"});

MATCH (A:Student {name: "Alice"}), (B:Student {name: "Bob"})


CREATE (A)-[:FRIEND]->(B), (B)-[:FRIEND]->(A);

MATCH (B:Student {name: "Bob"}), (C:Student {name: "Charlie"})


CREATE (B)-[:FRIEND]->(C), (C)-[:FRIEND]->(B);

MATCH (C:Student {name: "Charlie"}), (D:Student {name: "David"})


CREATE (C)-[:FRIEND]->(D), (D)-[:FRIEND]->(C);

MATCH (D:Student {name: "David"}), (A:Student {name: "Alice"})


CREATE (D)-[:FRIEND]->(A), (A)-[:FRIEND]->(D);

MATCH (S:Student), (VIT:Institution {name: "Vishnu Institute of Technology"})


CREATE (S)-[:STUDENT_OF]->(VIT);
B) Create Hobbies and Link Them to Students

CREATE (Hobby1:Hobby {name: "Music"}),


(Hobby2:Hobby {name: "Gaming"}),
(Hobby3:Hobby {name: "Reading"});

MATCH (A:Student {name: "Alice"}), (Hobby1:Hobby {name: "Music"})


CREATE (A)-[:HAS_HOBBY]->(Hobby1);

MATCH (B:Student {name: "Bob"}), (Hobby2:Hobby {name: "Gaming"})


CREATE (B)-[:HAS_HOBBY]->(Hobby2);

MATCH (C:Student {name: "Charlie"}), (Hobby1:Hobby {name: "Music"})


CREATE (C)-[:HAS_HOBBY]->(Hobby1);

MATCH (D:Student {name: "David"}), (Hobby3:Hobby {name: "Reading"})


CREATE (D)-[:HAS_HOBBY]->(Hobby3);
C) View Student, Has_Hobby, and Friends Relationship

MATCH (s:Student)-[:HAS_HOBBY]->(h:Hobby)
RETURN s.name AS Student, h.name AS Hobby;

MATCH (s:Student)-[:FRIEND]->(f:Student)
RETURN s.name AS Student, f.name AS Friend;
D) View All Nodes and Relationships

MATCH (n)
RETURN n;

MATCH (n)-[r]->(m)
RETURN n, r, m;
E) Change the Music Hobby to "Movies"

MATCH (h:Hobby {name: "Music"})


SET h.name = "Movies";
F) Delete Bob, Gaming, and Their Relationships

MATCH (b:Student {name: "Bob"})-[r]-()


DELETE r, b;

MATCH (g:Hobby {name: "Gaming"})-[r]-()


DELETE r, g;

MATCH (n)-[r]->(m)
RETURN n, r, m;

You might also like