Skip to content

Cassandra with the Node.js driver

Uses cassandra-driver 4.10. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.

cass-1.example.com,cass-2.example.com
machnosql-1.example.com,machnosql-2.example.com

The address comes from the environment variable CASSANDRA_CONTACT_POINTS, so switching to MachNoSQL changes configuration only.

Terminal window
export CASSANDRA_CONTACT_POINTS='machnosql-1.example.com,machnosql-2.example.com'
npm install
npm start

Credentials come from CASSANDRA_USERNAME and CASSANDRA_PASSWORD, the local data center from CASSANDRA_DC (default dc1).

The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.

app.js
// Sensor readings on Cassandra, unchanged on MachNoSQL.
import cassandra from "cassandra-driver";
const client = new cassandra.Client({
contactPoints: process.env.CASSANDRA_CONTACT_POINTS.split(","),
localDataCenter: process.env.CASSANDRA_DC ?? "dc1",
credentials: { username: process.env.CASSANDRA_USERNAME, password: process.env.CASSANDRA_PASSWORD },
});
await client.connect();
await client.execute(
"CREATE KEYSPACE IF NOT EXISTS iot WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3}",
);
await client.execute(
"CREATE TABLE IF NOT EXISTS iot.readings (sensor text, at timestamp, value double, PRIMARY KEY (sensor, at)) WITH CLUSTERING ORDER BY (at DESC)",
);
await client.execute("CREATE TABLE IF NOT EXISTS iot.sensors (sensor text PRIMARY KEY, owner text)");
const now = Date.now();
for (let minute = 0; minute < 10; minute++) {
await client.execute(
"INSERT INTO iot.readings (sensor, at, value) VALUES (?, ?, ?) USING TTL 86400",
["s-1", new Date(now - minute * 60_000), 20 + minute / 10],
{ prepare: true },
);
}
const result = await client.execute(
"SELECT at, value FROM iot.readings WHERE sensor = ? AND at > ? LIMIT 5",
["s-1", new Date(now - 5 * 60_000)],
{ prepare: true },
);
for (const row of result.rows) {
console.log(row.at, row.value);
}
const lwt = await client.execute(
"INSERT INTO iot.sensors (sensor, owner) VALUES (?, ?) IF NOT EXISTS",
["s-1", "ada"],
{ prepare: true },
);
console.log("registered:", lwt.wasApplied());
await client.shutdown();
package.json
{
"name": "machnosql-example-cassandra-node",
"private": true,
"type": "module",
"scripts": { "start": "node app.js" },
"dependencies": { "cassandra-driver": "^4.10.0" }
}