UNPKG

9.39 kBMarkdownView Raw
1# DataStax Node.js Driver for Apache Cassandra
2
3A modern, [feature-rich](#features) and highly tunable Node.js client library for Apache Cassandra (1.2+) and DataStax Enterprise (3.1+) using exclusively Cassandra's binary protocol and Cassandra Query Language v3.
4
5## Installation
6
7```bash
8$ npm install cassandra-driver
9```
10
11[![Build Status](https://travis-ci.org/datastax/nodejs-driver.svg?branch=master)](https://travis-ci.org/datastax/nodejs-driver)
12
13## Features
14
15- Simple, Prepared, and Batch statements
16- Asynchronous IO, parallel execution, request pipelining
17- [Connection pooling][pooling]
18- Auto node discovery
19- Automatic reconnection
20- Configurable [load balancing][load-balancing] and [retry policies][retry]
21- Works with any cluster size
22- [Row streaming and pipes](#avoid-buffering)
23
24## Documentation
25
26- [Documentation index][doc-index]
27- [CQL types to javascript types][doc-datatypes]
28- [API docs][doc-api]
29- [FAQ][faq]
30
31## Getting Help
32
33You can use the [project mailing list][mailinglist] or create a ticket on the [Jira issue tracker][jira].
34
35## Upgrading from 1.x branch
36
37If you are upgrading from the 1.x branch of the driver, be sure to have a look at the [upgrade guide][upgrade1].
38
39## Basic usage
40
41```javascript
42var cassandra = require('cassandra-driver');
43var client = new cassandra.Client({ contactPoints: ['h1', 'h2'], keyspace: 'ks1'});
44var query = 'SELECT email, last_name FROM user_profiles WHERE key=?';
45client.execute(query, ['guy'], function(err, result) {
46 assert.ifError(err);
47 console.log('got user profile with email ' + result.rows[0].email);
48});
49```
50
51### Prepare your queries
52
53Using prepared statements provides multiple benefits.
54Prepared statements are parsed and prepared on the Cassandra nodes and are ready for future execution.
55Also, when preparing, the driver retrieves information about the parameter types which
56 **allows an accurate mapping between a JavaScript type and a Cassandra type**.
57
58The driver will prepare the query once on each host and execute the statement with the bound parameters.
59
60```javascript
61//Use query markers (?) and parameters
62var query = 'UPDATE user_profiles SET birth=? WHERE key=?';
63var params = [new Date(1942, 10, 1), 'jimi-hendrix'];
64//Set the prepare flag in the query options
65client.execute(query, params, {prepare: true}, function(err) {
66 assert.ifError(err);
67 console.log('Row updated on the cluster');
68});
69```
70
71### Avoid buffering
72
73When using `#eachRow()` and `#stream()` methods, the driver parses each row as soon as it is received,
74 yielding rows without buffering them.
75
76```javascript
77//Reducing a large result
78client.eachRow('SELECT time, val FROM temperature WHERE station_id=', ['abc'],
79 function(n, row) {
80 //the callback will be invoked per each row as soon as they are received
81 minTemperature = Math.min(row.val, minTemperature);
82 },
83 function (err) {
84 assert.ifError(err);
85 }
86);
87```
88
89The `#stream()` method works in the same way but instead of callback it returns a [Readable Streams2][streams2] object
90 in `objectMode` that emits instances of `Row`.
91It can be **piped** downstream and provides automatic pause/resume logic (it buffers when not read).
92
93```javascript
94client.stream('SELECT time, val FROM temperature WHERE station_id=', ['abc'])
95 .on('readable', function () {
96 //readable is emitted as soon a row is received and parsed
97 var row;
98 while (row = this.read()) {
99 console.log('time %s and value %s', row.time, row.val);
100 }
101 })
102 .on('end', function () {
103 //stream ended, there aren't any more rows
104 })
105 .on('error', function (err) {
106 //Something went wrong: err is a response error from Cassandra
107 });
108```
109
110### User defined types
111
112[User defined types (UDT)][cql-udt] are represented as Javascript objects.
113
114For example:
115Consider the following UDT and table
116```cql
117CREATE TYPE address (
118 street text,
119 city text,
120 state text,
121 zip int,
122 phones set<text>
123);
124CREATE TABLE users (
125 name text PRIMARY KEY,
126 email text,
127 address frozen<address>
128);
129```
130
131You can retrieve the user address details as a regular Javascript object.
132
133```javascript
134var query = 'SELECT name, email, address FROM users WHERE name = ?';
135client.execute(query, [name], { prepare: true}, function (err, result) {
136 var row = result.first();
137 var address = row.address;
138 console.log('User lives in %s, %s - %s', address.street, address.city, address.state);
139});
140```
141
142Read more information about using [UDTs with the Node.js Driver][doc-udt].
143
144### Paging
145
146All driver methods use a default `fetchSize` of 5000 rows, retrieving only first page of results up to a
147 maximum of 5000 rows to shield an application against accidentally large result sets. To retrieve the following
148 records you can use the `autoPage` flag in the query options of `#eachRow()` and `#stream()` methods.
149
150```javascript
151//Imagine a column family with millions of rows
152var query = 'SELECT * FROM largetable';
153client.eachRow(query, [], {autoPage: true}, function (n, row) {
154 //This function will be called per each of the rows in all the table
155}, endCallback);
156```
157
158### Batch multiple statements
159
160You can execute multiple statements in a batch to update/insert several rows atomically even in different column families.
161
162```javascript
163var queries = [
164 {
165 query: 'UPDATE user_profiles SET email=? WHERE key=?',
166 params: [emailAddress, 'hendrix']
167 },
168 {
169 query: 'INSERT INTO user_track (key, text, date) VALUES (?, ?, ?)',
170 params: ['hendrix', 'Changed email', new Date()]
171 }
172];
173client.batch(queries, { prepare: true }, function(err) {
174 assert.ifError(err);
175 console.log('Data updated on cluster');
176});
177```
178
179----
180
181## Data types
182
183There are few data types defined in the ECMAScript specification, this usually represents a problem when you are trying
184 to deal with data types that come from other systems in Javascript.
185
186The driver supports all the CQL data types in Apache Cassandra (2.2 and below) even for types that no built-in
187Javascript representation exists, like decimal, varint and bigint. Check the documentation on working with
188 [numerical values][doc-numerical], [uuids][doc-uuid] and [collections][doc-collections].
189
190## Logging
191
192Instances of `Client()` are `EventEmitter` and emit `log` events:
193```javascript
194client.on('log', function(level, className, message, furtherInfo) {
195 console.log('log event: %s -- %s', level, message);
196});
197```
198The `level` being passed to the listener can be `verbose`, `info`, `warning` or `error`.
199
200## Feedback Requested
201
202**Help us focus our efforts!** Provide your input on the [Platform and Runtime Survey][survey] (we kept it short).
203
204## Credits
205
206This driver is based on the original work of [Jorge Bay][jorgebay] on [node-cassandra-cql][old-driver] and adds a series of advanced features that are common across all other [DataStax drivers][drivers] for Apache Cassandra.
207
208The 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][old-driver] will be discontinued.
209
210## License
211
212Copyright 2015 DataStax
213
214Licensed 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
215
216http://www.apache.org/licenses/LICENSE-2.0
217
218Unless 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.
219
220[cassandra]: http://cassandra.apache.org/
221[doc-api]: http://docs.datastax.com/en/drivers/nodejs/2.2/Client.html
222[doc-index]: http://docs.datastax.com/en/developer/nodejs-driver/2.2/
223[doc-datatypes]: http://docs.datastax.com/en/developer/nodejs-driver/2.2/nodejs-driver/reference/nodejs2Cql3Datatypes.html
224[doc-numerical]: http://docs.datastax.com/en/developer/nodejs-driver/2.2/nodejs-driver/reference/numericalValues.html
225[doc-uuid]: http://docs.datastax.com/en/developer/nodejs-driver/2.2/nodejs-driver/reference/uuids-timeuuids.html
226[doc-collections]: http://docs.datastax.com/en/developer/nodejs-driver/2.2/nodejs-driver/reference/collections.html
227[doc-udt]: http://docs.datastax.com/en/developer/nodejs-driver/2.2/nodejs-driver/reference/userDefinedTypes.html
228[faq]: http://docs.datastax.com/en/developer/nodejs-driver/2.2/nodejs-driver/faq/njdFaq.html
229[load-balancing]: http://docs.datastax.com/en/developer/nodejs-driver/2.2/common/drivers/reference/tuningPolicies.html
230[retry]: http://docs.datastax.com/en/developer/nodejs-driver/2.2/common/drivers/reference/tuningPolicies.html#retry-policy
231[pooling]: http://docs.datastax.com/en/developer/nodejs-driver/2.2/nodejs-driver/reference/poolingConfiguration.html
232[upgrade1]: https://github.com/datastax/nodejs-driver/blob/master/doc/upgrade-guide-2.0.md
233[old-driver]: https://github.com/jorgebay/node-cassandra-cql
234[jorgebay]: https://github.com/jorgebay
235[drivers]: https://github.com/datastax
236[mailinglist]: https://groups.google.com/a/lists.datastax.com/forum/#!forum/nodejs-driver-user
237[jira]: https://datastax-oss.atlassian.net/projects/NODEJS/issues
238[streams2]: http://nodejs.org/api/stream.html#stream_class_stream_readable
239[cql-udt]: http://cassandra.apache.org/doc/cql3/CQL.html#createTypeStmt
240[survey]: http://goo.gl/forms/f216tY3Ebr
\No newline at end of file