### Install Project Dependencies Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/CONTRIBUTING.md Install all necessary project dependencies using npm. This command should be run after cloning the repository. ```shell npm install ``` -------------------------------- ### Install cassandra-driver Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/README.md Install the Node.js driver for Apache Cassandra using npm. ```bash $ npm install cassandra-driver ``` -------------------------------- ### Delete Query Example Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/speculative-executions/README.md This is an example of a DELETE query that, if run after a speculative execution of an INSERT, could lead to unintuitive results due to request ordering. ```sql delete from my_table where k = 1; ``` -------------------------------- ### Get Selected Fields of Objects Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/queries/README.md Use the `fields` option in the `find()` method to retrieve only specific properties of the objects. This example gets only the name and description of videos. ```javascript const result = await videoMapper.find({ userId }, { fields: ['name', 'description' ]}); ``` -------------------------------- ### Insert Query Example Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/speculative-executions/README.md This is an example of an INSERT query that might be affected by speculative executions if the first execution is slow. ```sql insert into my_table (k, v) values (1, 1); ``` -------------------------------- ### Get Objects with Specific Order Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/queries/README.md Use the `orderBy` option in the `find()` method to sort the results. This example retrieves videos posted by a user, sorted by `addedDate` in descending order. ```javascript const result = await videoMapper.find({ userId }, { orderBy: { 'addedDate': 'desc' }}); ``` -------------------------------- ### Get an Iterable of Objects Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/queries/README.md Use the `find()` method to retrieve an iterable of objects that match the specified filter. This example retrieves all videos posted by a user. ```javascript const result = await videoMapper.find({ userId }); ``` -------------------------------- ### Querying with User-Defined Aggregates Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/udfs/README.md Example of how to query data using a user-defined aggregate like 'avg'. Ensure the aggregate is properly defined in Cassandra. ```javascript const query = 'SELECT avg(salary) as salary FROM employees'; client.execute(query) .then(function (result) { const row = result.first(); console.log('Average salary %d', row.salary); }); ``` -------------------------------- ### Configure DSE GSSAPI Authentication Provider Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/auth/README.md Use the 'authProvider' option with DseGssapiAuthProvider for GSSAPI authentication in DSE. Ensure the 'kerberos' dependency is installed. ```javascript const cassandra = require('cassandra-driver'); const client = new cassandra.Client({ contactPoints, localDataCenter, authProvider: new cassandra.auth.DseGssapiAuthProvider() }); ``` -------------------------------- ### Get a Single Object Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/queries/README.md Use the `get()` method to retrieve a single object matching the provided primary keys. Returns null if no object is found. ```javascript const video = await videoMapper.get({ videoId }); ``` -------------------------------- ### Execute Query with Numeric Parameter Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/README.md This example shows a basic execution of a query with a numeric parameter. It may fail if the inferred JavaScript type (e.g., Number as double) does not match the target CQL column type (e.g., int). ```javascript const key = 1000; client.execute('SELECT * FROM table1 where key = ?', [ key ]); ``` -------------------------------- ### Find Objects with Multiple Conditions Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/queries/README.md Use the `q.and()` operator within `find()` to apply multiple conditions on the same field. This example finds videos added between two dates. ```javascript const result = await videoMapper.find({ userId, addedDate: q.and(q.gte(beginDate), q.lt(endDate)) }); ``` -------------------------------- ### Creating and Inserting Vector Values Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/collections/README.md Vectors are represented by `cassandra.types.Vector`. This example demonstrates creating a keyspace, table with a vector column, and inserting values using both simple and prepared statements. Note the use of `cassandra.types.Integer.fromInt` and specifying the vector element type. ```javascript await c.connect() .then(() => c.execute("drop keyspace if exists test")) .then(() => c.execute("create KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}")) .then(() => c.execute("create table test.foo(i varint primary key, j vector)")) .then(() => c.execute("create custom index ann_index on test.foo(j) using 'StorageAttachedIndex'")) // Base inserts using simple and prepared statements .then(() => c.execute(`insert into test.foo (i, j) values (?, ?)`, [cassandra.types.Integer.fromInt(1), new cassandra.types.Vector([8, 2.3, 58], 'float')])) .then(() => c.execute(`insert into test.foo (i, j) values (?, ?)`, [cassandra.types.Integer.fromInt(5), new cassandra.types.Vector([23, 18, 3.9])], {prepare: true})); ``` -------------------------------- ### Find Objects with Relational Operator Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/queries/README.md Use the `find()` method with relational operators from the `q` module to filter objects based on conditions like 'greater than'. This example finds videos added after a specific date. ```javascript const result = await videoMapper.find({ userId, addedDate: q.gt(myDate) }); ``` -------------------------------- ### Hint Target Data Type for Query Parameter Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/README.md Alternatively, you can explicitly hint the target data type for a parameter in the query options. This example specifies that the first parameter should be treated as an integer. ```javascript // Hint that the first parameter is an integer client.execute('SELECT * FROM table1 where key = ?', [ key ], { hints : ['int'] }); ``` -------------------------------- ### Insert Selected Fields of an Object Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/queries/README.md Use the `fields` option with `insert()` to specify which properties of an object should be inserted. This example inserts only the id, name, and added date. ```javascript await videoMapper.insert(video, { fields: ['videoId', 'name', 'description'] }); ``` -------------------------------- ### Retrieve Tuple Value Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/tuples/README.md Demonstrates how to query and access values within a retrieved tuple using the `get(index)` method. Ensure the table schema includes a `frozen>` column. ```javascript const query = 'SELECT name, time, currencies, value FROM forex where name = ?'; client.execute(query, [name], { prepare: true }) .then(function (result) { result.rows.forEach(function (row) { console.log('%s to %s: %s', row.currencies.get(0), row.currencies.get(1), row.value); }); }); ``` -------------------------------- ### Define Custom Type Conversions Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/defining-mappings/README.md Implement `fromModel` and `toModel` functions within column mappings to transform property values to and from CQL column values. This example converts a JSON string column to a JavaScript Object. ```javascript const mappingOptions = { models: { 'User': { tables: ['users'], mappings: new UnderscoreCqlToCamelCaseMappings(), columns: { 'userid': 'userId', 'info': { name: 'user_info', fromModel: JSON.stringify, toModel: JSON.parse } } } } }; await userMapper.insert({ userId, info: { birthdate, favoriteBrowser } }); ``` -------------------------------- ### Prepare and Execute a Query Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/README.md Prepare a query with placeholders (?) and execute it with bound parameters. This is beneficial for performance and type safety. Ensure the 'prepare: true' option is set. ```javascript // Use query markers (?) and parameters const query = 'UPDATE users SET birth = ? WHERE key=?'; const params = [ new Date(1942, 10, 1), 'jimi-hendrix' ]; // Set the prepare flag in the query options await client.execute(query, params, { prepare: true }); console.log('Row updated on the cluster'); ``` -------------------------------- ### Initialize Cassandra Client Instance Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/coding-rules/README.md Create a new Client instance for connecting to a Cassandra cluster. Configure contact points and the local data center. This instance should be long-lived and shared across the application. ```javascript const cassandra = require('cassandra-driver'); const client = new cassandra.Client({ contactPoints: ['10.1.1.3', '10.1.1.4', '10.1.1.5'], localDataCenter: 'us-east-1' }); ``` -------------------------------- ### Initialize Cassandra Client Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/getting-started/README.md Instantiate a Cassandra Client with connection details. This client is designed to be long-lived. ```javascript const cassandra = require('cassandra-driver'); const Client = cassandra.Client; const Mapper = cassandra.mapping.Mapper; const client = new Client({ contactPoints, localDataCenter, keyspace }); ``` -------------------------------- ### Connect to a Cassandra Cluster Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/getting-started/README.md Instantiate a Client and connect to your Cassandra cluster by providing contact points and the local data center name. It's recommended to create a single Client instance for your application. ```javascript const cassandra = require('cassandra-driver'); const client = new cassandra.Client({ contactPoints: ['host1', 'host2'], localDataCenter: 'datacenter1' }); client.connect(); ``` -------------------------------- ### Configure Plain-Text Authentication Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/auth/README.md Set the 'credentials' option when creating a Client instance for plain-text authentication. ```javascript const cassandra = require('cassandra-driver'); const client = new cassandra.Client({ contactPoints, localDataCenter, credentials: { username: 'my_username', password: 'my_p@ssword1!' } }); ``` -------------------------------- ### Define Basic Model Mappings Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/defining-mappings/README.md Configure table names and the naming convention for a model. Use `UnderscoreCqlToCamelCaseMappings` to convert snake_case CQL names to camelCase model properties. ```javascript const UnderscoreCqlToCamelCaseMappings = cassandra.mapping.UnderscoreCqlToCamelCaseMappings; const mappingOptions = { models: { 'User': { tables: ['users'], mappings: new UnderscoreCqlToCamelCaseMappings() } } }; // Create the Mapper using the mapping options const mapper = new Mapper(client, mappingOptions); ``` -------------------------------- ### Get Model Mapper Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/getting-started/README.md Obtain a ModelMapper for a specific model. This can be called multiple times with no additional cost. ```javascript const videoMapper = mapper.forModel('Video'); ``` -------------------------------- ### Setting Default Graph Options Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/graph-support/README.md Illustrates how to configure default graph options, such as the graph name, during client initialization. ```APIDOC ## Client Initialization with Graph Options ### Description Configure default graph options when initializing the `Client` to be used for all graph statements. ### Example ```javascript const client = new cassandra.Client({ contactPoints: ['host1', 'host2'], localDataCenter: 'dc1', graphOptions: { name: 'demo' } }); ``` ### Overriding Options with Execution Profiles Default graph options can be overridden by specifying an execution profile when calling `executeGraph()`. ### Example ```javascript // Use a different graph name than the one provided when creating the client instance const result = await client.executeGraph(query, params, { executionProfile: 'graph-oltp' }); ``` ``` -------------------------------- ### Retrieve a Single Object Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/getting-started/README.md Use the `get()` method of a ModelMapper to retrieve a single object based on its primary key. ```javascript const video = await videoMapper.get({ videoId: myVideoId }); ``` -------------------------------- ### Manual Paging: Fetch First Page Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/paging/README.md Execute a query and retrieve the first page of results. Store the `pageState` to resume fetching from this point later. ```javascript const options = { prepare: true , fetchSize: 1000 }; const result = await client.execute(query, parameters, options); // Property 'rows' will contain only the amount of items of the first page (max 1000 in this case) const rows = result.rows; // Store the page state let pageState = result.pageState; ``` -------------------------------- ### List Loaded Keyspaces Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/metadata/README.md Logs the names of all keyspaces that have been loaded into the metadata object after the client connects. ```javascript console.log(Object.keys(client.metadata.keyspaces)); ``` -------------------------------- ### Initialize Client with Default Graph Options Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/graph-support/README.md Set default graph options, such as the graph name, during `Client` initialization to avoid specifying them in every `executeGraph()` call. ```javascript const cassandra = require('cassandra-driver'); const client = new cassandra.Client({ contactPoints: ['host1', 'host2'], localDataCenter: 'dc1', graphOptions: { name: 'demo' } }); ``` -------------------------------- ### Update Selected Fields of an Object Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/queries/README.md Use the `fields` option with `update()` to specify which properties of an object should be updated. This example updates only the name and added date. ```javascript await videoMapper.update(video, { fields: ['videoId', 'name', 'description'] }); ``` -------------------------------- ### Configure PlainTextAuthProvider for Authentication Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/getting-started/README.md Set up PlainTextAuthProvider with username and password for connecting to an auth-enabled Cassandra cluster. This provider is then passed to the Client constructor. ```javascript const authProvider = new cassandra.auth.PlainTextAuthProvider('my_user', 'p@ssword1!'); //Set the auth provider in the clientOptions when creating the Client instance const client = new Client({ contactPoints, localDataCenter, authProvider }); ``` -------------------------------- ### Configure Client with Custom Promise Factory Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/promise-callback/README.md Optionally provide a custom promise factory, such as one from Bluebird, when creating a new Client instance to control Promise creation. ```javascript const BbPromise = require('bluebird'); const client = new Client({ contactPoints, localDataCenter, promiseFactory: BbPromise.fromCallback }); ``` -------------------------------- ### Create and Insert Tuple Value Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/tuples/README.md Shows how to create a new `Tuple` instance using its constructor and then insert it into a Cassandra table. Requires importing `Tuple`, `BigDecimal`, and `TimeUuid` from `cassandra-driver`.types. ```javascript const { Tuple, BigDecimal, TimeUuid } = require('cassandra-driver').types; // Create a new instance of a Tuple. const currencies = new Tuple('USD', 'EUR'); const query = 'INSERT INTO forex (name, time, currencies, value) VALUES (?, ?, ?, ?)'; const params = ['market1', TimeUuid.now(), currencies, new BigDecimal(1, 0)]; client.execute(query, params, { prepare: true }); ``` -------------------------------- ### Get Connection Pool State Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/connection-pooling/README.md Retrieve the current state of connection pools to each host. This includes the number of open connections and in-flight queries for each connected host. ```javascript const state = client.getState(); for (let host of state.getConnectedHosts()) { console.log('Host %s: open connections = %d; in flight queries = %d', host.address, state.getOpenConnections(host), state.getInFlightQueries(host)); } ``` -------------------------------- ### Enable Client Certificate Authentication with TLS/SSL Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/tls/README.md Configure client certificate authentication by providing `key`, `cert`, and optionally `ca` properties within `sslOptions`. `rejectUnauthorized` should be set to `true` if the server requires client certificate authentication. ```javascript const sslOptions = { // Necessary only if the server requires client certificate authentication. key: fs.readFileSync('client-key.pem'), cert: fs.readFileSync('client-cert.pem'), // Necessary only if the server uses a self-signed certificate. ca: [ fs.readFileSync('server-cert.pem') ], rejectUnauthorized: true }; const client = new Client({ contactPoints, localDataCenter, sslOptions }); ``` -------------------------------- ### Decode UUID from Cassandra Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/uuids/README.md Cassandra `uuid` data type values are decoded as instances of the `Uuid` class. This example shows how to check the instance type and convert it to a string. ```javascript client.execute('SELECT id FROM users') .then(function (result) { console.log(result.rows[0].id instanceof Uuid); // true console.log(result.rows[0].id.toString()); // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx }); ``` -------------------------------- ### Execute Prepared Statement Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/coding-rules/README.md Execute a query using a prepared statement by setting the 'prepare' flag in query options. This optimizes repeated executions of the same query with different parameters. ```javascript const query = 'SELECT id, name FROM users WHERE id = ?'; client.execute(query, [ id ], { prepare: true }); ``` -------------------------------- ### Decoding CQL Decimal as BigDecimal Instances Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/numerical/README.md CQL decimal datatype values are decoded by the driver as instances of the BigDecimal class. This example verifies the type of a decoded decimal value. ```javascript client.execute('SELECT decimal_val FROM users') .then(function (result) { console.log(result.rows[0]['decimal_val'] instanceof BigDecimal); // true }); ``` -------------------------------- ### Basic Usage: Execute a Query Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/README.md Connect to a Cassandra cluster and execute a simple SELECT query. Uses the promise-based API for asynchronous operations. Requires contact points, local data center, and keyspace configuration. ```javascript const cassandra = require('cassandra-driver'); const client = new cassandra.Client({ contactPoints: ['h1', 'h2'], localDataCenter: 'datacenter1', keyspace: 'ks1' }); const query = 'SELECT name, email FROM users WHERE key = ?'; client.execute(query, [ 'someone' ]) .then(result => console.log('User with email %s', result.rows[0].email)); ``` -------------------------------- ### Retrieve Nested UDT Data with Node.js Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/udts/README.md Access nested UDT fields as nested JavaScript objects. This example demonstrates accessing data from a UDT containing another UDT. ```javascript const query = 'SELECT name, email, address FROM users WHERE id = ?'; client.execute(query, [name], { prepare: true }) .then(function (result) { const row = result.first(); const address = row.address; // phones is an Array of Objects address.phones.forEach(phone => console.log('Phone %s: %s', phone.alias, phone.phone_number)); }); ``` -------------------------------- ### Configure Request Tracking Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/logging/README.md Instantiate RequestLogger with thresholds for slow queries and/or large requests. Pass this instance to the Client constructor to enable tracking. ```javascript const cassandra = require('cassandra-driver'); const requestTracker = new cassandra.tracker.RequestLogger({ slowThreshold: 1000 }); const client = new Client({ contactPoints, localDataCenter, requestTracker }); ``` -------------------------------- ### Decoding Numerical Types as JavaScript Numbers Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/numerical/README.md When decoding CQL int, float, and double values, they are returned as JavaScript Numbers. This example demonstrates checking the type of decoded values. ```javascript client.execute('SELECT int_val, float_val, double_val FROM tbl') .then(function (result) { console.log(typeof result.rows[0]['int_val']); // Number console.log(typeof result.rows[0]['float_val']); // Number console.log(typeof result.rows[0]['double_val']); // Number }); ``` -------------------------------- ### Decoding CQL Varint as Integer Instances Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/numerical/README.md CQL varint datatype values are decoded by the driver as instances of the Integer class. This example verifies that a decoded varint value is an instance of Integer. ```javascript client.execute('SELECT varint_val FROM users') .then(function (result) { console.log(result.rows[0]['varint_val'] instanceof Integer); // true }); ``` -------------------------------- ### Decoding CQL Bigint as Long Instances Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/numerical/README.md CQL bigint datatype values are decoded by the driver as instances of the Long class. This example checks if a decoded bigint value is an instance of Long. ```javascript client.execute('SELECT bigint_val FROM users') .then(function (result) { console.log(result.rows[0]['bigint_val'] instanceof Long); // true }); ``` -------------------------------- ### Inserting Map Values (with prepare) Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/collections/README.md To successfully insert JavaScript Objects as CQL map values, queries must be prepared. Setting the `prepare: true` option in query options allows the driver to handle this automatically. ```javascript client.execute(query, params, { prepare: true }); ``` -------------------------------- ### Decode TimeUUID from Cassandra Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/uuids/README.md CQL `timeuuid` data type values are decoded as `TimeUuid` instances, which inherit from `Uuid`. This example demonstrates checking the instance types and accessing the stored date. ```javascript client.execute('SELECT id, timeid FROM sensor') .then(function (result) { console.log(result.rows[0].timeid instanceof TimeUuid); // true console.log(result.rows[0].timeid instanceof Uuid); // true, it inherits from Uuid console.log(result.rows[0].timeid.toString()); // <- xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx console.log(result.rows[0].timeid.getDate()); // <- Date stored in the identifier }); ``` -------------------------------- ### Create Mapper Instance Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/getting-started/README.md Create a Mapper instance, optionally defining model mappings. Reuse this instance throughout your application. ```javascript const mapper = new Mapper(client, { models: { 'Video': { tables: ['videos'] } } }); ``` -------------------------------- ### Executing Graph Queries Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/graph-support/README.md Demonstrates how to execute graph queries using the `executeGraph()` method with both Promise-based and callback-based approaches. ```APIDOC ## executeGraph() ### Description Executes a graph query against the database. ### Method `client.executeGraph(query, params, options)` ### Parameters - **query** (string) - The graph traversal query to execute. - **params** (object, optional) - An object containing named parameters for the query. - **options** (object, optional) - Options for query execution, such as `executionProfile`. ### Request Example (Promise-based) ```javascript client.executeGraph('g.V()') .then(function (result) { const vertex = result.first(); console.log(vertex.label); }); ``` ### Request Example (Callback-based) ```javascript client.executeGraph('g.V()', function (err, result) { assert.ifError(err); const vertex = result.first(); // ... }); ``` ### Response - **result** (GraphResultSet) - An iterable object containing the results of the graph query. ``` -------------------------------- ### Initialize Cluster with Custom Execution Profile Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/execution-profiles/README.md Create a custom execution profile named 'aggregation' with specific settings and include it when initializing the Cassandra client. This profile can then be referenced by its name. ```javascript const aggregationProfile = new ExecutionProfile('aggregation', { consistency: consistency.localQuorum, loadBalancing: new DCAwareRoundRobinPolicy('us-west'), retry: myRetryPolicy, readTimeout: 30000, serialConsistency: consistency.localSerial }); const client = new Client({ contactPoints: ['host1'], localDataCenter, profiles: [ aggregationProfile ] }); ``` -------------------------------- ### Configure Max Schema Agreement Wait Time Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/metadata/README.md Creates a new client instance with a customized maximum wait time for schema agreement, specified in seconds. ```javascript const client = new Client({ contactPoints, localDataCenter, protocolOptions: { maxSchemaAgreementWaitSeconds: 20 } }); ``` -------------------------------- ### Inserting Map Values (without prepare) Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/collections/README.md Directly inserting a JavaScript Object as a map value without preparing the statement will result in a TypeError because the driver cannot infer the target data type. This example shows the error. ```javascript const query = 'INSERT INTO tbl (id, map_val) VALUES (?, ?)'; const params = [id, {key1: 1, key2: 2}]; client.execute(query, params) .catch(function (err) { console.log(err) // TypeError: The target data type could not be guessed }); ``` -------------------------------- ### Specify Keyspace on Client Instance Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/limitations-and-faq/README.md When using a single keyspace, set the keyspace name during Client instantiation for simpler configuration. ```javascript const client = new Client({ contactPoints, localDataCenter, keyspace: 'killrvideo' }); const mapper = new Mapper(client); ``` -------------------------------- ### Using Long for CQL Bigint Datatype Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/numerical/README.md The Long class from 'cassandra-driver'.types is used for CQL bigint values, providing support for 64-bit integers which are not natively handled by JavaScript. This example demonstrates creating and manipulating Long instances. ```javascript const Long = require('cassandra-driver').types.Long; const value1 = Long.fromNumber(101); const value2 = Long.fromString('101'); console.log(value1.toString()); // 101 console.log(value2.toString()); // 101 console.log(value1.equals(value2)); // true console.log(value1.add(value2).toString()); // 202 ``` -------------------------------- ### Configure Execution Profiles for Mixed Workloads Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/getting-started/README.md Define multiple Execution Profiles for different workloads (e.g., time-series, graph) within a single Client instance. Each profile can have specific configurations like consistency, timeouts, and load balancing. ```javascript const client = new cassandra.Client({ contactPoints: ['host1'], localDataCenter: 'oltp-us-west', profiles: [ new ExecutionProfile('time-series', { consistency: consistency.localOne, readTimeout: 30000, serialConsistency: consistency.localSerial }), new ExecutionProfile('graph', { loadBalancing: new DefaultLoadBalancingPolicy('graph-us-west'), consistency: consistency.localQuorum, readTimeout: 10000, graphOptions: { name: 'myGraph' } }) ] }); // Use an execution profile for a CQL query client.execute('SELECT * FROM system.local', null, { executionProfile: 'time-series' }); // Use an execution profile for a gremlin query client.executeGraph('g.V().count()', null, { executionProfile: 'graph' }); ``` -------------------------------- ### Execute Mapper methods with Execution Profiles Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/queries/README.md Specify an execution profile name as the last argument to Mapper methods to apply custom execution options. This can be done for various operations like get, find, update, and insert. ```javascript videoMapper.get({ videoid }, 'oltp-sample'); videoMapper.find({ userId }, 'oltp-sample'); // After the document info videoMapper.find({ userId }, { fields: ['name', 'description'] }, 'oltp-sample'); videoMapper.update(video, 'oltp-sample'); videoMapper.insert(video, { ifNotExists: true }, 'oltp-sample'); // Use default execution profile userMapper.get({ videoId }); // Use another execution profile userMapper.get({ videoId }, 'another-execution-profile'); ``` -------------------------------- ### Initialize Cluster with Default and Named Profiles Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/execution-profiles/README.md Define a 'default' execution profile to provide fallback settings for other profiles. This is useful for setting common options like consistency or read timeout that can be overridden by specific named profiles. ```javascript const client = new Client({ contactPoints: ['host1'], localDataCenter, profiles: [ new ExecutionProfile('default', { consistency: consistency.one, readTimeout: 10000 }), new ExecutionProfile('graph-oltp', { consistency: consistency.localQuorum, graphOptions: { name: 'myGraph' } }) ] }); ``` -------------------------------- ### Using BigDecimal for CQL Decimal Datatype Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/numerical/README.md The BigDecimal class from 'cassandra-driver'.types is used to represent CQL decimal values, as JavaScript lacks native arbitrary precision decimal support. This example shows creating and comparing BigDecimal instances. ```javascript const BigDecimal = require('cassandra-driver').types.BigDecimal; const value1 = new BigDecimal(153, 2); const value2 = BigDecimal.fromString('1.53'); console.log(value1.toString()); // 1.53 console.log(value2.toString()); // 1.53 console.log(value1.equals(value2)); // true ``` -------------------------------- ### Using Integer for CQL Varint Datatype Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/numerical/README.md The Integer class, adapted from Google Closure, is used for CQL varint values, enabling support for arbitrarily large signed integers in JavaScript. This example shows creating and operating on Integer instances. ```javascript const Integer = require('cassandra-driver').types.Integer; const value1 = Integer.fromNumber(404); const value2 = Integer.fromString(404); console.log(value1.toString()); // 404 console.log(value2.toString()); // 404 console.log(value1.equals(value2)); // true console.log(value1.add(value2).toString()); // 808 ``` -------------------------------- ### Execute Query Using Execution Profile Instance Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/execution-profiles/README.md Pass the actual `ExecutionProfile` instance to the options object when executing a query. This is an alternative to using the profile's name. ```javascript client.execute(query, params, { executionProfile: aggregationProfile }); ``` -------------------------------- ### Minimum Configuration for Astra Connection Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/cloud/README.md Use the `cloud.secureConnectBundle` option with the path to your zip file and provide your CQL credentials. This is the minimum configuration required for connecting to DataStax Astra. ```javascript const client = new Client({ cloud: { secureConnectBundle: 'path/to/secure-connect-DATABASE_NAME.zip' }, credentials: { username: 'user_name', password: 'p@ssword1' } }); ``` -------------------------------- ### Prepare Query for Accurate Type Mapping Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/README.md Using prepared statements is recommended to ensure accurate mapping between JavaScript and Cassandra types. This approach parses and prepares the statement on Cassandra nodes, allowing the driver to correctly infer parameter types. ```javascript // Prepare the query before execution client.execute('SELECT * FROM table1 where key = ?', [ key ], { prepare : true }); ``` -------------------------------- ### Execute Batch Statements with Promises Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/batch/README.md Use the `batch()` method with promises to execute a list of queries atomically. Prepare queries for optimal performance and correct type mapping. The entire batch succeeds or fails. ```javascript const query1 = 'UPDATE user_profiles SET email = ? WHERE key = ?'; const query2 = 'INSERT INTO user_track (key, text, date) VALUES (?, ?, ?)'; const queries = [ { query: query1, params: [emailAddress, 'hendrix'] }, { query: query2, params: ['hendrix', 'Changed email', new Date()] } ]; // Promise-based call client.batch(queries, { prepare: true }) .then(function() { // All queries have been executed successfully }) .catch(function(err) { // None of the changes have been applied }); ``` -------------------------------- ### Execute Batch Statements with Callbacks Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/batch/README.md Execute a list of queries atomically using the callback-based invocation of the `batch()` method. Prepare queries for optimal performance and correct type mapping. The entire batch succeeds or fails. ```javascript client.batch(queries, { prepare: true }, function (err) { // All queries have been executed successfully // Or none of the changes have been applied, check err }); ``` -------------------------------- ### Retrieve Objects with Mapper Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/README.md Use the `find` method to retrieve objects from the database. Execution methods return a Promise, so async functions are recommended for use. ```javascript const videos = await videoMapper.find({ userId }); for (let video of videos) { console.log(video.name); } ``` -------------------------------- ### Set Default Consistency Level Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/getting-started/README.md Configure a default consistency level for all queries when initializing the Client. This avoids repetitive configuration for each query. ```javascript const client = new Client({ queryOptions: { consistency: types.consistencies.localQuorum }, // ... rest of the options }); ``` -------------------------------- ### Configure Client with Custom Address Translator Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/address-resolution/README.md Instantiate your custom AddressTranslator and provide it within the client options under policies.addressResolution. Note that contact points provided during client initialization are not translated. ```javascript const client = new Client({ contactPoints, localDataCenter, policies: { addressResolution: new MyAddressTranslator() } }); ``` -------------------------------- ### Execute Query with Parameters Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/getting-started/README.md Use parameter markers (?) in your CQL query and provide an array of values to prevent CQL injection and improve readability. This method is suitable for queries with changing parameters. ```javascript const query = 'SELECT name, email, birthdate FROM users WHERE key = ?'; const result = await client.execute(query, ['mick-jagger']); ``` -------------------------------- ### Run Local Tests Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/CONTRIBUTING.md Execute unit and integration tests locally. This command uses mocha to run the test suite. ```shell npx mocha test/unit test/integration/short --recursive --exit ``` -------------------------------- ### Listen for Driver Log Events Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/logging/README.md Subscribe to the 'log' event on the Client instance to receive logging information. The level can be 'verbose', 'info', 'warning', or 'error'. Use 'info' and above for production. ```javascript client.on('log', (level, loggerName, message, furtherInfo) => { console.log(`${level} - ${loggerName}: ${message}`); }); ``` -------------------------------- ### Insert and Retrieve Geospatial Point Data with Node.js Driver Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/geotypes/README.md Demonstrates how to insert a Point object and retrieve it using the Cassandra Node.js driver. The retrieved point can be checked for its type and accessed for its coordinates. ```javascript const cassandra = require('cassandra-driver'); const Point = cassandra.geometry.Point; const insertQuery = 'INSERT INTO points_of_interest (name, coords) VALUES (?, ?)'; const selectQuery = 'SELECT coords FROM points_of_interest WHERE name = ?'; await client.execute(insertQuery, [ 'Eiffel Tower', new Point(48.8582, 2.2945) ]); const result = await client.execute(selectQuery, [ 'Eiffel Tower' ]); const row = result.first(); const point = row['coords']; console.log(point instanceof Point); // true console.log('x: %d, y: %d', point.x, point.y); // x: 48.8582, y: 2.2945 console.log(point.toString()); // 'POINT (48.8582 2.2945)' ``` -------------------------------- ### Retrieving User-Defined Function Metadata Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/udfs/README.md Demonstrates how to retrieve metadata for a specific user-defined function by providing its keyspace, name, and parameter types. This is useful for understanding function signatures and properties. ```javascript client.metadata.getFunction('ks1', 'iif', ['boolean', 'int']) .then(function (err, udf) { console.log('Function metadata %j', udf); }); ``` -------------------------------- ### Using Named Parameters in Graph Queries Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/graph-support/README.md Demonstrates how to pass named parameters to graph traversal queries. ```APIDOC ## Graph Query Parameters ### Description Graph traversal execution supports named parameters. Parameters must be passed in as an object. ### Example ```javascript const traversal = 'g.addV(vertexLabel).property("name", username)'; await client.executeGraph(traversal, { vertexLabel: 'person', username: 'marko' }); ``` ``` -------------------------------- ### Define and use Execution Profiles Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/queries/README.md Configure execution options like consistency level and read timeout by defining `ExecutionProfile` instances when creating the `Client`. These profiles can then be specified during Mapper method calls. ```javascript const client = new Client({ contactPoints, localDataCenter, profiles: [ new ExecutionProfile('default', { consistency: consistency.one, readTimeout: 10000 }), new ExecutionProfile('oltp-sample', { consistency: consistency.localQuorum }) ] }); ``` -------------------------------- ### Enable Client-to-Node TLS/SSL Encryption Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/tls/README.md Use `sslOptions` with `rejectUnauthorized: true` to enable client-to-node TLS/SSL encryption. This ensures the client verifies the identity of the Cassandra nodes. ```javascript const client = new Client({ contactPoints, localDataCenter, sslOptions: { rejectUnauthorized: true }}}); await client.connect(); ``` -------------------------------- ### Retrieve UDT Data with Node.js Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/udts/README.md Retrieve user address details as a regular JavaScript object. Ensure the 'prepare' flag is set for accurate UDT field mapping. ```javascript const query = 'SELECT name, email, address FROM users WHERE id = ?'; client.execute(query, [name], { prepare: true }) .then(function (result) { const row = result.first(); const address = row.address; console.log('User lives in %s - %s', address.city, address.state); }); ``` -------------------------------- ### Execute Prepared Statement Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/getting-started/README.md For frequently reused queries, use prepared statements by setting the 'prepare: true' option. This enhances performance by allowing the Cassandra node to parse the query only once. ```javascript // Recommended: use query markers for parameters const query = 'SELECT name, email, birthdate FROM users WHERE key = ?'; // Recommended: set the prepare flag in your queryOptions const result = await client.execute(query, ['mick-jagger'], { prepare: true }); ``` -------------------------------- ### Change DSE Driver Import to Cassandra Driver Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/upgrade-guide/upgrade-from-dse-driver/README.md To upgrade, change the import statement from 'dse-driver' to 'cassandra-driver' for the Client class. ```javascript const { Client } = require('dse-driver'); const client = new Client({ contactPoints: ['host1', 'host2'], localDataCenter: 'datacenter1' }); ``` ```javascript const { Client } = require('cassandra-driver'); const client = new Client({ contactPoints: ['host1', 'host2'], localDataCenter: 'datacenter1' }); ``` -------------------------------- ### Configure Connections Per Host Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/connection-pooling/README.md Set the number of core connections per host based on distance (local or remote). This configuration is part of the client options when initializing the driver. ```javascript const cassandra = require('cassandra-driver'); const distance = cassandra.types.distance; const options = { contactPoints, localDataCenter, pooling: { coreConnectionsPerHost: { [distance.local]: 2, [distance.remote]: 1 } } }; const client = new Client(options); ``` -------------------------------- ### Find User Videos with Object Mapper Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/getting-started/README.md Use the object mapper to retrieve documents based on a userId. Requires the mapper to be configured. ```javascript const userVideos = await videoMapper.find({ userId }); for (let video of userVideos) { console.log(video.name); } ``` -------------------------------- ### Retrieve and Log Table Definition Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/metadata/README.md Fetches the definition of a specific table and logs its name and column details. Handles concurrent requests efficiently by querying only once. ```javascript client.metadata.getTable('ks1', 'table1') .then(function (tableInfo) { console.log('Table %s', table.name); table.columns.forEach(function (column) { console.log('Column %s with type %j', column.name, column.type); }); }); ``` -------------------------------- ### Output Cluster Host Information Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/metadata/README.md Iterates through connected hosts and logs their address, datacenter, and rack. This information is automatically updated by the driver. ```javascript client.hosts.forEach(function (host) { console.log(host.address, host.datacenter, host.rack); }); ``` -------------------------------- ### Insert Data into Cassandra Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/getting-started/README.md Use the execute() method with an INSERT statement and parameters to add data to your Cassandra table. Ensure parameters are provided in the correct order. ```javascript const query = 'INSERT INTO users (key, name, email, birthdate) VALUES (?, ?, ?)'; const params = ['mick-jagger', 'Sir Mick Jagger', 'mick@rollingstones.com', new Date(1943, 6, 26)]; await client.execute(query, params, { prepare: true }); ``` -------------------------------- ### Create custom ModelMapper method with mapWithQuery Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/queries/README.md Define a custom Mapper method to execute a specific CQL query and map the results. Use query markers (?) for parameters and provide a function to extract parameters from an object. ```javascript // Write your own query using query markers for parameters const query = 'SELECT COUNT(videoid) as video_count FROM user_videos WHERE userid = ? GROUP BY userid'; // Create a new ModelMapper method with your own query // and a function to extract the parameters from an object videoMapper.getCount = videoMapper.mapWithQuery(query, video => [ video.userId ]); ``` -------------------------------- ### Enable Loopback Aliases on macOS Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/CONTRIBUTING.md On macOS, enable loopback aliases for testing purposes. This command adds aliases to the loopback interface. ```shell for i in {2..255}; do sudo ifconfig lo0 alias 127.0.0.$i up; done ``` -------------------------------- ### Manual Paging: Fetch Next Page Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/paging/README.md Use the previously stored `pageState` in the query options to fetch the next set of rows. Update `pageState` with the new value for subsequent requests. ```javascript // Use the pageState in the queryOptions to continue where you left it. const options = { pageState, prepare: true, fetchSize: 1000 }; const result = await client.execute(query, parameters, options); // Following rows up to fetch size (1000) const rows = result.rows; // Store the next paging state. pageState = result.pageState; ``` -------------------------------- ### Configuring ECMAScript Map and Set Support Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/collections/README.md To use native ECMAScript 6 Map and Set objects for CQL map and set types, specify the `Map` and `Set` constructors in the client options during client initialization. ```javascript const options = { contactPoints, localDataCenter, encoding: { map: Map, set: Set } }; const client = new Client(options); ``` -------------------------------- ### Configure Constant Speculative Execution Policy Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/speculative-executions/README.md Initialize the Cassandra client with a `ConstantSpeculativeExecutionPolicy`. This policy triggers additional executions after a specified delay and up to a maximum number of times. ```javascript const { Client, policies } = require('cassandra-driver'); const ConstantSpeculativeExecutionPolicy = policies.speculativeExecution.ConstantSpeculativeExecutionPolicy; const client = new Client({ contactPoints, policies: { speculativeExecution: new ConstantSpeculativeExecutionPolicy( 200, // delay before a new execution is launched 2) // maximum amount of additional executions } }); ``` -------------------------------- ### Using Graph Types and UDTs Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/graph-support/README.md Explains how to use TinkerPop and DSE graph types, including custom User-Defined Types (UDTs), with the driver. ```APIDOC ## Graph Types and User-Defined Types (UDTs) ### Description The driver supports various TinkerPop and DSE graph types. For types without native JavaScript representation, the `types` module is provided. User-defined types (UDTs) are supported using JavaScript objects and the `asUdt()` function. ### Example with Native Types ```javascript const { types } = require('cassandra-driver'); const { Uuid, InetAddress } = types; const traversal = 'g.addV("sample").property("uid", uid).property("ip_address", address)'; await client.execute(traversal, { uid: Uuid.random(), address: InetAddress.fromString('10.0.0.100') }); ``` ### Example with User-Defined Types (UDTs) ```javascript const { datastax } = require('cassandra-driver'); const { asUdt } = datastax.graph; // Get the UDT metadata const udtInfo = await client.metadata.getUdt(graphName, 'address'); // Build the UDT const address = asUdt({ street: '123 Priam St.', city: 'My City', state: 'MY' }, udtInfo); const traversal = 'g.addV("sample").property("uid", uid).property("user_address", address)'; // Use the UDT as parameter await client.execute(traversal, { uid: Uuid.random(), address }); ``` ``` -------------------------------- ### Execute Query Using Default Execution Profile Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/execution-profiles/README.md When no execution profile is explicitly provided in the options for `client.execute`, the driver automatically uses the 'default' execution profile if one is defined, or the client's default settings. ```javascript client.execute(query, params, null); ``` -------------------------------- ### Configurable Settings for Astra Connection Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/cloud/README.md In addition to the secure connection bundle and credentials, you can specify a default keyspace. Do not set `contactPoints` or `sslOptions` when using `secureConnectBundle`. ```javascript const client = new Client({ cloud: { secureConnectBundle: 'path/to/secure-connect-DATABASE_NAME.zip' }, credentials: { username: 'user_name', password: 'p@ssword1' }, keyspace: 'my_ks' }); ``` -------------------------------- ### Map a Model to Multiple Tables Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/mapper/defining-mappings/README.md Configure a single model to map to multiple tables or views for efficient reads and mutations. Specify table names in `MappingOptions`. ```javascript const mappingOptions = { models: { 'Video': { tables: [ 'videos', 'user_videos', 'latest_videos' ], mappings: new UnderscoreCqlToCamelCaseMappings(), columns: { 'videoid': 'videoId', 'userid': 'userId' } } } }; // The following invocation will create a batch inserting a row on each of the tables await videoMapper.insert({ videoId, userId, addedDate, yyyymmdd, name }); // The following call will use table `user_videos` to get videos by user id const result = await videoMapper.find({ userId }); ``` -------------------------------- ### Initialize Client with EC2MultiRegionTranslator Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/address-resolution/README.md Use the out-of-the-box EC2MultiRegionTranslator to optimize network costs in multi-region EC2 deployments. This translator automatically uses private IP addresses for nodes within the same region and public IP addresses for nodes in different regions. ```javascript const cassandra = require('cassandra-driver'); const { EC2MultiRegionTranslator } = cassandra.policies.addressResolution; const client = new cassandra.Client({ contactPoints, localDataCenter, policies: { addressResolution: new EC2MultiRegionTranslator() } }); ``` -------------------------------- ### Reading List and Set Values Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/datatypes/collections/README.md When reading CQL list or set columns, the driver returns them as native JavaScript Arrays. This snippet demonstrates checking the type of retrieved values. ```javascript client.execute('SELECT list_val, set_val, double_val FROM tbl') .then(function (result) { console.log(Array.isArray(result.rows[0]['list_val'])); // true console.log(Array.isArray(result.rows[0]['set_val'])); // true }); ``` -------------------------------- ### Set Max Protocol Version to Highest Supported Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/native-protocol/README.md Allow the driver to use the highest protocol version supported by both the driver and the Cassandra cluster. This is the default behavior. ```javascript const client = new Client({ contactPoints, localDataCenter, protocolOptions: { maxVersion: protocolVersion.maxSupported } }); ``` -------------------------------- ### Execute Graph Query with Promise Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/graph-support/README.md Use the `executeGraph()` method to run graph queries. It returns a Promise that resolves with the result set. ```javascript const client = new cassandra.Client({ contactPoints: ['host1', 'host2'], localDataCenter: 'dc1', graphOptions: { name: 'demo' } }); // executeGraph() method returns a Promise client.executeGraph('g.V()') .then(function (result) { const vertex = result.first(); console.log(vertex.label); }); ``` -------------------------------- ### Execute Query Using Execution Profile by Name Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/execution-profiles/README.md Specify the execution profile to use for a query by passing its name in the options object. This allows you to leverage the pre-configured settings for that profile. ```javascript client.execute(query, params, { executionProfile: 'aggregation' }); ``` -------------------------------- ### Execute Query with Promise API Source: https://github.com/apache/cassandra-nodejs-driver/blob/trunk/doc/features/promise-callback/README.md Use the promise-based API for executing queries. When no callback is provided, the execute method returns a Promise. ```javascript client.execute('SELECT name, email FROM users') .then(result => console.log('User with email %s', result.rows[0].email)); ```