Building web server with Cassandra database
Installation
First, You need to install the Cassandra database server on your local computer. In the mac os, You can install it with homebrew. Open the terminal, and install the cassandra database with brew.
$ brew install cassandra
If you don’t have brew, you need to install brew first.
$ /bin/bash -c “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
After downloading the Cassandra, you can turn on the Cassandra database, You can do it with brew.
$ brew services start cassandra
Also you can stop it.
$ brew services stop cassandra
After the database server starts, you can open the cqlsh for a query to the local Cassandra server. You just type the cqlsh on your terminal.
$ cqlsh
Now installation is done. You can also use docker to install and start the Cassandra database, but I don’t use docker for now.
Make the keyspace and table
Cassandra Keyspace is a data container inside of a Cassandra database system. A keyspace is an outermost object in a Cassandra cluster that controls how data replicates on nodes. You can make multiple keyspaces on your Cassandra database system. I just make one simple keyspace to local. Be careful you MUST do it with single quotes not double quotes.
cqlsh> CREATE KEYSPACE awesome_db WITH REPLICATION = { ‘class’ : ‘SimpleStrategy’, ‘replication_factor’: 1 };
This query makes a keyspace named awesome_db
, so now we can make tables to the awesome_db and connect to awesome_db
keyspace. After creating the keyspace, let’s make the table an awesome_db
keyspace.
cqlsh> CREATE TABLE awesome_db.users (id int PRIMARY KEY, name text, email text);
I make the users table to awesome_db keyspace and make it with three fields named id, name, and email. In the table, it’s required that at least one field is set as a primary key. In this sample, id is the primary key. You can check data types from this article: CQL data types | CQL for Cassandra 3.x
You can check the table using CQL. don’t forget the semicolon. Now the table is made successfully.
cqlsh> SELECT * FROM awesome_db.users;
id | email | name
- - + - - - -+ - - -
(0 rows)
CQL CRUD
Now you need to know how to query with CQL. This query will using at your client server.
CREATE
You can use INSERT INTO
to add data to the table.
cqlsh> INSERT INTO {KEYSPACE.TABLE_NAME} (fields) VALUES (values);
cqlsh> INSERT INTO awesome_db.users (id, email, name) VALUES (0, 'sample@email.com', 'Sample name');
READ
You can use SELECT FROM
to read data from the table.
cqlsh> SELECT {FIELDS} FROM {KEYSPACE.TABLE_NAME};
cqlsh> SELECT * FROM awesome_db.users;
UPDATE
You can use UPDATE SET and WHERE
to update the column. Be careful use this as this might make all columns change.
cqlsh> UPDATE {KEYSPACE.TABLE_NAME} SET {FIELD = UPDATED VALUE} WHERE {FIELD = WHERE};
cqlsh> UPDATE awesome_db.users SET name = 'updated sample' WHERE id = 0;
DELETE
You can delete columns with DELETE
and also be careful this also makes delete all columns.
cqlsh> DELETE FROM {KEYSPACE.TABLE_NAME} WHERE {FIELD = WHERE};
cqlsh> DELETE FROM awesome_db.users WHERE id = 0;
You can refer to entire scripts from documents: CQL commands | CQL for Cassandra 3.x. Find what you need and make it yourself.
Make API server with Express (node) and Cassandra.
Now You can make the express server but it is okay with other server frameworks even plain nodeJS. You can use spring boot (java or Kotlin), Fastify (node), django (Python), and so on. So let’s make some server with your favourite architecture. This time, I will use the express.
You need to install the nodejs, and then automatically install the npm.
$ mkdir express-server
$ cd express-server
$ npm init -y
After that you need to install the express for making an API server.
$ npm install express
Also we’re downloading the nodemon package for node development, It will automatically restart the server when server code is changed.
$ npm install nodemon — save-dev
And you need to make a node package as a module to handle the import statement. Add "type":"module"
to your package.json
. You also edit scripts for starting your server.
"type": "module",
"scripts": {
"start": "node src/app.js",
"dev": "nodemon src/app.js"
},
Make the src
folder, and make the app.js
file to the src folder.
import express from 'express';
const app = express();
app.get("/", (req, res) => {
res.send("hello world");
});
app.listen(3000, () => {
console.log("server will be start at 3000 port")
});
Now, Let’s make some connections with Cassandra. We’ll install the Cassandra driver to connect between express and cassandra.
$ npm install cassandra-driver
You need to adding this to your app.js
file
import cassandra from "cassandra-driver";
const client = new cassandra.Client({
contactPoints: ['127.0.0.1'],
localDataCenter: 'datacenter1',
keyspace: "awesome_db"
});
app.get("/api/users", async (req, res) => {
// CQL
const query = 'SELECT * FROM users';
// QUERYING
const response = await client.execute(query);
// Response to client
res.send(response.rows);
})
After running your server, You can see the response from /api/users
routes.
$ npm run dev
$ curl localhost:3000/api/users
This is all. Now you can add the query, execute, and more validations.
Sample code: https://github.com/techhtml/express-cassandra