Represents a database client that maintains multiple connections to the cluster nodes, providing methods to execute CQL statements.

The Client uses policies to decide which nodes to connect to, which node to use per each query execution, when it should retry failed or timed-out executions and how reconnection to down nodes should be made.

Global
This class is global

Augments

Events

hostAdd

Emitted when a new host is added to the cluster.

  • Host The host being added.

hostDown

Emitted when a host in the cluster changed status from up to down.

  • host The host that changed the status.

hostRemove

Emitted when a host is removed from the cluster

  • Host The host being removed.

hostUp

Emitted when a host in the cluster changed status from down to up.

  • host The host that changed the status.

Members

HostMap

hosts

Gets an associative array of cluster hosts.

String

keyspace

Gets the name of the active keyspace.

Metadata

metadata

Gets the schema and cluster metadata information.

ClientMetrics

metrics

The ClientMetrics instance used to expose measurements of its internal behavior and of the server as seen from the driver side.

By default, a DefaultMetrics instance is used.

Constructor

new

Client

(ClientOptions options)

Creates a new instance of Client.

Examples:
Creating a new client instance
const client = new Client({
  contactPoints: ['10.0.1.101', '10.0.1.102'],
  localDataCenter: 'datacenter1'
});
Executing a query
const result = await client.connect();
console.log(`Connected to ${client.hosts.length} nodes in the cluster: ${client.hosts.keys().join(', ')}`);
Executing a query
const result = await client.execute('SELECT key FROM system.local');
const row = result.first();
console.log(row['key']);
Parameters:
Name Type Description
options ClientOptions

The options for this instance.

Methods

batch

(Array<string> or Array<{query, params}> queries, [QueryOptions options], [ResultCallback callback])

Executes batch of queries on an available connection to a host.

It returns a Promise when a callback is not provided.

Parameters:
Name Type Description
queries Array<string> or Array<{query, params}>

The queries to execute as an Array of strings or as an array of object containing the query and params

options optional QueryOptions

The query options.

callback optional ResultCallback

Executes callback(err, result) when the batch was executed

connect

([function callback])

Attempts to connect to one of the contactPoints and discovers the rest the nodes of the cluster.

When the Client is already connected, it resolves immediately.

It returns a Promise when a callback is not provided.

Examples:
Usage example
await client.connect();
Parameters:
Name Type Description
callback optional function

The optional callback that is invoked when the pool is connected or it failed to connect.

eachRow

(String query, [Array or Object params], [QueryOptions options], function rowCallback, [function callback])

Executes the query and calls rowCallback for each row as soon as they are received. Calls the final callback after all rows have been sent, or when there is an error.

The query can be prepared (recommended) or not depending on the prepare flag.

Examples:
Using per-row callback and arrow functions
client.eachRow(query, params, { prepare: true }, (n, row) => console.log(n, row), err => console.error(err));
Overloads
client.eachRow(query, rowCallback);
client.eachRow(query, params, rowCallback);
client.eachRow(query, params, options, rowCallback);
client.eachRow(query, params, rowCallback, callback);
client.eachRow(query, params, options, rowCallback, callback);
Parameters:
Name Type Description
query String

The query to execute

params optional Array or Object

Array of parameter values or an associative array (object) containing parameter names as keys and its value.

options optional QueryOptions

The query options.

rowCallback function

Executes rowCallback(n, row) per each row received, where n is the row index and row is the current Row.

callback optional function

Executes callback(err, result) after all rows have been received.

When dealing with paged results, ResultSet#nextPage() method can be used to retrieve the following page. In that case, rowCallback() will be again called for each row and the final callback will be invoked when all rows in the following page has been retrieved.

execute

(String query, [Array or Object params], [QueryOptions options], [ResultCallback callback])

Executes a query on an available connection.

The query can be prepared (recommended) or not depending on the prepare flag.

Some execution failures can be handled transparently by the driver, according to the RetryPolicy or the SpeculativeExecutionPolicy used.

It returns a Promise when a callback is not provided.

Examples:
Promise-based API, using async/await
const query = 'SELECT name, email FROM users WHERE id = ?';
const result = await client.execute(query, [ id ], { prepare: true });
const row = result.first();
console.log('%s: %s', row['name'], row['email']);
Callback-based API
const query = 'SELECT name, email FROM users WHERE id = ?';
client.execute(query, [ id ], { prepare: true }, function (err, result) {
  assert.ifError(err);
  const row = result.first();
  console.log('%s: %s', row['name'], row['email']);
});
Parameters:
Name Type Description
query String

The query to execute.

params optional Array or Object

Array of parameter values or an associative array (object) containing parameter names as keys and its value.

options optional QueryOptions

The query options for the execution.

callback optional ResultCallback

Executes callback(err, result) when execution completed. When not defined, the method will return a promise.

executeGraph

(String query, [Object or null parameters], [GraphQueryOptions or null options], [function callback])

Executes a graph query.

It returns a Promise when a callback is not provided.

Examples:
Promise-based API, using async/await
const result = await client.executeGraph('g.V()');
// Get the first item (vertex, edge, scalar value, ...)
const vertex = result.first();
console.log(vertex.label);
Callback-based API
client.executeGraph('g.V()', (err, result) => {
  const vertex = result.first();
  console.log(vertex.label);
});
Iterating through the results
const result = await client.executeGraph('g.E()');
for (let edge of result) {
  console.log(edge.label); // created
});
Using result.forEach()
const result = await client.executeGraph('g.V().hasLabel("person")');
result.forEach(function(vertex) {
  console.log(vertex.type); // vertex
  console.log(vertex.label); // person
});
Parameters:
Name Type Description
query String

The gremlin query.

parameters optional Object or null

An associative array containing the key and values of the parameters.

options optional GraphQueryOptions or null

The graph query options.

callback optional function

Function to execute when the response is retrieved, taking two arguments: err and result. When not defined, the method will return a promise.

getReplicas

(String keyspace, Buffer token)

Gets the host that are replicas of a given token.

Parameters:
Name Type Description
keyspace String
token Buffer
Returns:
Type Description
Array<Host>

getState

()

Gets a snapshot containing information on the connections pools held by this Client at the current time.

The information provided in the returned object only represents the state at the moment this method was called and it’s not maintained in sync with the driver metadata.

Returns:
Type Description
ClientState

A ClientState instance.

shutdown

([function callback])

Closes all connections to all hosts.

It returns a Promise when a callback is not provided.

Parameters:
Name Type Description
callback optional function

Optional callback to be invoked when finished closing all connections.

stream

(String query, [Array or Object params], [QueryOptions options], [function callback])

Executes the query and pushes the rows to the result stream as soon as they received.

The stream is a ReadableStream object that emits rows. It can be piped downstream and provides automatic pause/resume logic (it buffers when not read).

The query can be prepared (recommended) or not depending on QueryOptions.prepare flag. Retries on multiple hosts if needed.

Parameters:
Name Type Description
query String

The query to prepare and execute.

params optional Array or Object

Array of parameter values or an associative array (object) containing parameter names as keys and its value

options optional QueryOptions

The query options.

callback optional function

executes callback(err) after all rows have been received or if there is an error

Returns:
Type Description
ResultStream