1

I was using such a following code to connect to only 1 keyspace:

This is `/config/db.ts:

import cassandra from "cassandra-driver";

class Cpool {
static _pool : cassandra.Client;

static connect(options : any){
  this._pool = new cassandra.Client(options);
}


  static execute(query: string, params?: cassandra.ArrayOrObject | undefined, options?: cassandra.QueryOptions | undefined)
  {
    return this._pool.execute(query, params, options);
  }
}


export { Cpool };

And the below code is the index.ts:

  const default_options = {
    contactPoints: [process.env.CONTACT_POINTS],
    localDataCenter: process.env.LOCAL_DATA_CENTER,
    keyspace: process.env.KEYSPACE,
  };

  try {
    await Cpool.connect(default_options);
    console.log("Connected to Cassandra");
  } catch (err) {
    console.log(err);
  }

Now I want to have 2 or more keyspaces but don't know should I create a new client in order to each of them or I can use only 1 client to connect to multiple keyspaces? How?

best_of_man
  • 643
  • 2
  • 15

2 Answers2

1

When you have multiple keyspaces in your database, you will need to fully qualify the tables in your query by explicitly specifying the keyspace name. For example:

query = "SELECT ... FROM keyspace_name.table_name WHERE ..."

or:

query = "INSERT INTO keyspace_name.table_name ... VALUES ..."

For best practice, only use one Client instance and reuse it for the life of your application. Cheers!

Erick Ramirez
  • 13,964
  • 1
  • 18
  • 23
  • Thank you but what can I do with `const default_options = { contactPoints: [process.env.CONTACT_POINTS], localDataCenter: process.env.LOCAL_DATA_CENTER, keyspace: process.env.KEYSPACE, };` When I should specify the keyspace while creating a client. – best_of_man Feb 10 '23 at 16:38
  • I use `default_options` to create a `client` like `await Cpool.connect(default_options);` and inside the `defailt_options` I am specifying the keyspace. How can I specify multiple keyspaces there? – best_of_man Feb 10 '23 at 16:46
  • You don't specify multiple keyspaces when you create the `Client` object -- you specify the keyspace with the table in your queries. Cheers! – Erick Ramirez Feb 13 '23 at 01:00
0

I found that it's not necessary to specify keyspace property while generating a Cassandra client and connect it to the Cassandra Database, so I changed:

  const default_options = {
    contactPoints: [process.env.CONTACT_POINTS],
    localDataCenter: process.env.LOCAL_DATA_CENTER,
    keyspace: process.env.KEYSPACE,
  };

To:

  const default_options = {
    contactPoints: [process.env.CONTACT_POINTS],
    localDataCenter: process.env.LOCAL_DATA_CENTER,
  };

And I specified keyspaces inside my queries instead, like INSERT INTO keyspace1.table_name ... in place of INSERT INTO table_name ....

best_of_man
  • 643
  • 2
  • 15