当前位置: 首页 > 软件库 > 数据库相关 > >

nodejs-driver

DataStax Node.js Driver for Apache Cassandra
授权协议 Apache-2.0 License
开发语言 Java
所属分类 数据库相关
软件类型 开源软件
地区 不详
投 递 者 羊舌源
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

DataStax Node.js Driver for Apache Cassandra®

A modern, feature-rich and highly tunable Node.js client library for Apache Cassandra and DSE usingexclusively Cassandra's binary protocol and Cassandra Query Language.

Installation

$ npm install cassandra-driver

Features

Documentation

Getting Help

You can use the project mailing list or create a ticket on the Jira issue tracker.

Basic usage

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));

The driver supports both promises and callbacks for the asynchronous methods,you can choose the approach that suits your needs.

Note that in order to have concise code examples in this documentation, we will use the promise-based API of thedriver along with the await keyword.

If you are using DataStax Astra you can configure your client by setting the secure bundle and theuser credentials:

const client = new cassandra.Client({
  cloud: { secureConnectBundle: 'path/to/secure-connect-DATABASE_NAME.zip' },
  credentials: { username: 'user_name', password: 'p@ssword1' }
});

Prepare your queries

Using prepared statements provides multiple benefits.

Prepared statements are parsed and prepared on the Cassandra nodes and are ready for future execution.Also, when preparing, the driver retrieves information about the parameter types whichallows an accurate mapping between a JavaScript type and a Cassandra type.

The driver will prepare the query once on each host and execute the statement with the bound parameters.

// 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');

Row streaming and pipes

When using #eachRow() and #stream() methods, the driver parses each row as soon as it is received,yielding rows without buffering them.

// Reducing a large result
client.eachRow(
  'SELECT time, val FROM temperature WHERE station_id=',
  ['abc'],
  (n, row) => {
    // The callback will be invoked per each row as soon as they are received
    minTemperature = Math.min(row.val, minTemperature); 
  },
  err => { 
    // This function will be invoked when all rows where consumed or an error was encountered  
  }
);

The #stream() method works in the same way but instead of callback it returns a Readable Streams2 objectin objectMode that emits instances of Row.

It can be piped downstream and provides automatic pause/resume logic (it buffers when not read).

client.stream('SELECT time, val FROM temperature WHERE station_id=', [ 'abc' ])
  .on('readable', function () {
    // 'readable' is emitted as soon a row is received and parsed
    let row;
    while (row = this.read()) {
      console.log('time %s and value %s', row.time, row.val);
    }
  })
  .on('end', function () {
    // Stream ended, there aren't any more rows
  })
  .on('error', function (err) {
    // Something went wrong: err is a response error from Cassandra
  });

User defined types

User defined types (UDT) are represented as JavaScript objects.

For example:Consider the following UDT and table

CREATE TYPE address (
  street text,
  city text,
  state text,
  zip int,
  phones set<text>
);
CREATE TABLE users (
  name text PRIMARY KEY,
  email text,
  address frozen<address>
);

You can retrieve the user address details as a regular JavaScript object.

const query = 'SELECT name, address FROM users WHERE key = ?';
const result = await client.execute(query, [ key ], { prepare: true });
const row = result.first();
const address = row.address;
console.log('User lives in %s, %s - %s', address.street, address.city, address.state);

Read more information about using UDTs with the Node.js Driver.

Paging

All driver methods use a default fetchSize of 5000 rows, retrieving only first page of results up to amaximum of 5000 rows to shield an application against accidentally retrieving large result sets in a single response.

stream() method automatically fetches the following page once the current one was read. You can also use eachRow()method to retrieve the following pages by using autoPage flag. See [paging documentation for moreinformation][doc-paging].

Batch multiple statements

You can execute multiple statements in a batch to update/insert several rows atomically even in different column families.

const queries = [
  {
    query: 'UPDATE user_profiles SET email=? WHERE key=?',
    params: [ emailAddress, 'hendrix' ]
  }, {
    query: 'INSERT INTO user_track (key, text, date) VALUES (?, ?, ?)',
    params: [ 'hendrix', 'Changed email', new Date() ]
  }
];

await client.batch(queries, { prepare: true });
console.log('Data updated on cluster');

Object Mapper

The driver provides a built-in object mapper that lets you interact with your data like youwould interact with a set of documents.

Retrieving objects from the database:

const videos = await videoMapper.find({ userId });
for (let video of videos) {
  console.log(video.name);
}

Updating an object from the database:

await videoMapper.update({ id, userId, name, addedDate, description });

You can read more information about getting started with the Mapper in ourdocumentation.


Data types

There are few data types defined in the ECMAScript specification, this usually represents a problem when you are tryingto deal with data types that come from other systems in JavaScript.

The driver supports all the CQL data types in Apache Cassandra (3.0 and below) even for types with no built-inJavaScript representation, like decimal, varint and bigint. Check the documentation on working withnumerical values, uuids and collections.

Logging

Instances of Client() are EventEmitter and emit log events:

client.on('log', (level, loggerName, message, furtherInfo) => {
  console.log(`${level} - ${loggerName}:  ${message}`);
});

The level being passed to the listener can be verbose, info, warning or error. Visit the loggingdocumentation for more information.

Compatibility

  • Apache Cassandra versions 2.1 and above.
  • DataStax Enterprise versions 4.8 and above.
  • Node.js versions 8 and above.

Note: DataStax products do not support big-endian systems.

Credits

This driver is based on the original work of Jorge Bay on node-cassandra-cql and adds a series of advanced features that are common across all other DataStax drivers for Apache Cassandra.

The development effort to provide an up to date, high performance, fully featured Node.js Driver for Apache Cassandra will continue on this project, while node-cassandra-cql will be discontinued.

License

© DataStax, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

 相关资料
  • Webstorm作为个javascript的IDE,提供了最天然的NodeJs支持,在Webstorm中,您可以运行、调试、自动提示NodeJs。 Webstorm 对 NodeJs 的支持 随便建个demo工程,建个 test.js,代码如下: var http = require('http'); server = http.createServer(function (req, res) {

  • Node.js 性能测试模拟器 Why? 性能测试时,可能需要一些系统外的被依赖服务的模拟器,常用性能测试工具如JMeter并没有模拟Server端的能力。如果是另外起个Tomcat,写些简单的模拟器——性能与容量是一个问题,因为被测试服务器集群可能有二十台机器,而跑模拟器的机器可能只有一两台。另一个是如果要快速修改输出内容,Tomcat的打包上传部署流程略显麻烦。 所以看上了Node.js。 另

  • Node.js 是运行在服务端的 JavaScript。 官网:https://haomo-tech.com 作者:毫末科技 邮箱:hxg@haomo-studio.com 官网:https://nodejs.org/en/ API文档:https://nodejs.org/dist/latest-v4.x/docs/api/ 教程:http://www.w3cschool.cn/nodejs/n

  • 截至2016年2月26日,官方的列表中,并没有提供NodeJS的Http API接口的封装。 - -! 好在我们有Github,在上面搜索到一个: https://github.com/node-influx/node-influx 项目介绍写着的是支持0.9x版本的InfluxDB,我在0.10上试了下,基本可用。 因为是纯Http API接口,如果某些接口有问题的话,可以直接给他 pull r

  • Node.js 事件循环 Node.js 是单进程单线程应用程序,但是因为 V8 引擎提供的异步执行回调接口,通过这些接口可以处理大量的并发,所以性能非常高。 Node.js 几乎每一个 API 都是支持回调函数的。 Node.js 基本上所有的事件机制都是用设计模式中观察者模式实现。 Node.js 单线程类似进入一个while(true)的事件循环,直到没有事件观察者退出,每个异步事件都生成一

  • 我正在学习NodeJS WriteStream。我无法理解函数调用的效果。如果以下示例中的调用不存在,会发生什么情况?我移除了它,但没有任何改变,在这两种情况下,结果都返回给客户机。

  •   KISSY 是淘宝网开发的一款轻巧灵活的JS框架,如今已经是1.1.7版本,并在淘宝网广泛应用,在浏览器端给我们带来更加清新的体验,今天让我们更进一步,我们 发起了nodejs-kissy 项目,你的 KISSY 程序可以无缝移植到服务器端了 ^_^ 示例代码: var S = require('kissy').KISSY;S.ready(function(S){ S.log('hello world!'); });

  • swig 是node端的一个优秀简洁的模板引擎,类似Python模板引擎Jinja,目前不仅在node端较为通用,相对于jade、ejs优秀,而且在浏览器端也可以很好地运行。 特性: 支持大多数主流浏览器。 表达式兼容性好。 面向对象的模板继承。 将过滤器和转换应用到模板中的输出。 可根据路劲渲染页面。 支持页面复用。 支持动态页面。 可扩展、可定制。 使用示例: 模板代码 <h1>{{ page