3

I am trying to get last inserted row in cassandra but I am getting undefined

Here is how code looks for insert:

const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1' });

let query = "INSERT INTO users (id, name, email ) values (uuid(), ?, ?)";

client.execute(query, [ 'badis', 'badis@badis.com' ])
  .then(result => console.log('User with id %s', result.rows[0].id));
Badis Merabet
  • 13,970
  • 9
  • 40
  • 55

1 Answers1

6

Remember you are dealing with NoSQL ("non relational")

If I were to run a SELECT * FROM users LIMIT 1 on this table, my result set would contain a single row. That row would be the one containing the lowest hashed value of username (my partition key), because that's how Cassandra stores data in the cluster. I would have no way of knowing if it was the last one added or not, so this wouldn't be terribly useful to you.

The workings are very different from those that you might be used to in MySQL.

If obtaining the last inserted row's information is needed for your system, then you will have to know it before you insert it.

Generating UUID

const Uuid = require('cassandra-driver').types.Uuid;
const id = Uuid.random();

Then you can use the id as another value for the prepared insert query

const cassandra = require('cassandra-driver');
const client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1' });

let query = "INSERT INTO users (id, name, email ) values (?, ?, ?)";

client.execute(query, [id, 'badis', 'badis@badis.com' ])
  .then(result => console.log('User with id %s', id));
EMX
  • 6,066
  • 1
  • 25
  • 32