Skip to content
Related Articles

Related Articles

How to update record in Cassandra using ExpressJS ?
  • Difficulty Level : Medium
  • Last Updated : 13 Apr, 2021

Apache Cassandra is a free and open-source, distributed, highly scalable, wide column store, NoSQL database management system. it is designed to handle large volumes of data, providing high availability with no single point of failure.

This article shows you that how to use Cassandra using express js and also shows how to update record in Cassandra using express Cassandra orm framework.

Features: The following features are used in this article.

  • To configure Cassandra docker container using docker hub.
  • To use express-cassandra orm framework for updating record in Cassandra using express js.
  • CQLSH(Cassandra Query Language Shell) command(s).

Example: This example creates Person Table in Cassandra data store with the following columns/attributes.

Javascript






module.exports = {
   fields:{
       name    : "text",
       surname : "text",
       age     : "int",
       created : "timestamp"
   },
   key:["name"]
}

Then it inserts one record using expressjs restful endpoint using express-cassandra

cqlsh> select * from test_ks.person;
name | age | created                         | surname
------+-----+---------------------------------+---------
John |  32 | 2021-04-02 11:05:00.946000+0000 |     Doe

Then it updates John(name column) record with surname Doe and age 55 with the help of express restful endpoint( please refer below Setting up Environment for updating record in Cassandra section further details).

cqlsh> select * from test_ks.person;
name | age | created                         | surname
------+-----+---------------------------------+---------
John |  55 | 2021-04-02 11:05:00.946000+0000 |     Doe
(1 rows)
cqlsh>

Applications:

  • Express-cassandra enables your nodejs app to manage a highly available distributed data store capable of handling a large dataset.
  • Express-cassandra empowers you to manage and query from nodejs like you are just dealing with javascript objects and methods.
  • Models are written as javascript modules and they automatically create the underlying DB tables. Then you can save, update, delete and query your data using the supported model method.
  • Its decouple nature allows you to use it with many popular node frameworks without much hassle.

Setting up Environment for updating record in Cassandra: Please find the following steps to update record in Cassandra using express js.

Step 1: To setup Cassandra server in docker container.

Please use the following docker commands.

  • docker pull cassandra:latest
  • docker run -d –name cassandra-node -p 9042:9042 cassandra
  • docker exec -it cassandra-node bash
  • cqlsh

Note: prerequisite is to install docker hub for running cassandra server in docker container.

Please use the following cqlsh command(s) to create keyspace and create a tutorial table in Cassandra to walk thru on how to update records in thar express.js application for the next steps.

  • CREATE KEYSPACE test_ks WITH replication = { ‘class’: ‘SimpleStrategy’, ‘replication_factor’:1};
  • use test_ks;

Step 2: To setup express js application.



Please find the following command(s)

  • mkdir mycassandratutorial
  • cd mycassandratutorial
  • npm init ( please feed all details like project name, author etc… )
  • npm install –save express
  • npm install express-cassandra

Note: prerequisite is to install node for running express js application.

Step 3: To setup cassandra connectivity using express-cassandra.

  • Please find the following index.js file, where it has configured Cassandra Server IP Address and Port number and schema etc.

index.js




var express = require('express');
var app = express();
var models = require('express-cassandra');
  
// Tell express-cassandra to use the models-directory, and
// use bind() to load the models using cassandra configurations.
models.setDirectory( __dirname + '/models').bind(
   {
       clientOptions: {
           contactPoints: ['127.0.0.1'],
           protocolOptions: { port: 9042 },
           keyspace: 'test_ks',
           queryOptions: {consistency: models.consistencies.one}
       },
       ormOptions: {
           defaultReplicationStrategy : {
               class: 'SimpleStrategy',
               replication_factor: 1
           },
           migration: 'safe'
       }
   },
   function(err) {
       if(err) throw err;
   }
);
node index

Note:

  • You’ll now have a `person` table in cassandra created against the model schema defined in the above Step No.1. please refer the following output.
root@76561f8b27a2:/# cqlsh
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.10 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
cqlsh> select * from test_ks.person;
name | age | created | surname
------+-----+---------+---------
(0 rows)
cqlsh>         
  • You can now access the model instance in `models.instance.Person` object containing supported orm operations.
  • Please find the following PersonModel.js file under models folder.

PersonModel.js




module.exports = {
   fields:{
       name    : "text",
       surname : "text",
       age     : "int",
       created : "timestamp"
   },
   key:["name"]
}

Note:Actually PersonModel.js maps into Cassandra table and does all the CRUD operation(s) using express-cassandra framework.

Step 4: To update record in Cassandra using express js restful API.

  • To create a restful end point for creating new Person record into Cassandra.

index.js




// code snippet from the index.js file
app.get('/person/:name/:surname/:age', function(req, res) {
   res.send('name: ' + req.params.name+', surname:'+req.params.surname+', age:'+req.params.age);
   var person = new models.instance.Person({
       name: req.params.name,
       surname: req.params.surname,
       age: parseInt(req.params.age),
       created: Date.now()
   });
   person.save(function(err){
       if(err) {
           console.log(err);
           return;
       }
       console.log('person saved!');
   });
});
  • You can access this end point  through web browser as http://localhost:3000/person/John/Doe/32 then you can get record created in Cassandra Person table. 
root@76561f8b27a2:/# cqlsh
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.10 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
cqlsh> select * from test_ks.person;
name | age | created                         | surname
------+-----+---------------------------------+---------
John |  32 | 2021-04-02 11:05:00.946000+0000 |     Doe
(1 rows)
cqlsh>
  • To update Person record from Cassandra through express js restful endpoint.

index.js




// code snippet from the index.js file 
app.put('/person/:name/:surname/:age?', function (req, res) {
   models.instance.Person.findOne({name: req.params.name }, function(err, person){
       if(err) throw err;
       if(person){
           if(req.params.surname){
               person.surname = req.params.surname;
           }
           if(req.params.age){
               person.age = parseInt(req.params.age);
           }
           person.save(function(err){
               if(err) console.log(err);
               else console.log('Person got updated...');
           });
       }
   });
   res.send('person updated');
 })
  • You can access this end point through curl command as below. 
    Note: the below curl command update(s) John Doe age from 32 to 55.
MINGW64 ~
$ curl -v -X PUT http://localhost:3000/person/John/Doe/55                                                               *   Trying 127.0.0.1:3000...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 3000 (#0)
> PUT /person/John/Doe/55 HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.67.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: text/html; charset=utf-8
< Content-Length: 14
< ETag: W/"e-TKKHGLrHAbIKlf0bIe4gdwzz0N0"
< Date: Fri, 02 Apr 2021 11:11:37 GMT
< Connection: keep-alive
<
person updated* Connection #0 to host localhost left intact
  • Please find the following Cassandra Person table output.
root@76561f8b27a2:/# cqlsh
Connected to Test Cluster at 127.0.0.1:9042.
[cqlsh 5.0.1 | Cassandra 3.11.10 | CQL spec 3.4.4 | Native protocol v4]
Use HELP for help.
cqlsh> select * from test_ks.person;
name | age | created                         | surname
------+-----+---------------------------------+---------
John |  55 | 2021-04-02 11:05:00.946000+0000 |     Doe
(1 rows)
cqlsh>
My Personal Notes arrow_drop_up
Recommended Articles
Page :