This repository has been archived by the owner on Nov 9, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathclient.js
804 lines (674 loc) · 30.4 KB
/
client.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
/**
ElasticSearch client implementation.
@module elastical
@submodule client
**/
var request = require('request').defaults({encoding: 'utf8'}),
util = require('./util'),
Index = require('./index'),
encode = encodeURIComponent;
/**
Creates a new Elastical client associated with the specified _host_. The client
uses ElasticSearch's REST API to interact with the host, so connections are
established as needed and are not persistent.
@example
// Create a client that connects to http://127.0.0.1:9200
var elastical = require('elastical'),
client = new elastical.client();
@class Client
@param {String} [host="127.0.0.1"] Hostname to connect to.
@param {Object} [options] Client options.
@param {String} [options.auth] Username and password (delimited by a ":") to
pass to ElasticSearch using basic HTTP auth. If not specified, no
authentication will be used. Be sure to set `options.protocol` to
'https' unless you're comfortable sending passwords in plaintext.
@param {Boolean} [options.curlDebug=false] If `true`, runnable curl commands
will be written to stderr for every request the client makes. This is
useful for debugging requests by hand.
@param {Number} [options.port=9200] Port to connect to.
@param {String} [options.protocol='http'] Protocol to use. May be "http" or
"https".
@param {Number} [options.timeout=60000] Number of milliseconds to wait
before aborting a request. Be sure to increase this if you do large bulk
operations.
@constructor
**/
function Client(host, options) {
// Allow options without host.
if (typeof host === 'object') {
options = host;
host = undefined;
}
this.host = host || '127.0.0.1';
this.options = options || {};
this.options.port || (this.options.port = 9200);
this.options.protocol || (this.options.protocol = 'http');
this.options.timeout || (this.options.timeout = 60000);
this._indexCache = {};
}
Client.prototype = {
// -- Protected Properties -------------------------------------------------
/**
Search options that must be passed as query parameters instead of in the
request body.
@property _SEARCH_PARAMS
@type {String[]}
@protected
@final
**/
_SEARCH_PARAMS: [
'preference', 'routing', 'scroll', 'scroll_id', 'search_type', 'timeout'
],
// -- Public Properties ----------------------------------------------------
/**
Base URL for this client, of the form "http://host:port".
@property baseUrl
@type {String}
**/
get baseUrl() {
return this.options.protocol + '://' +
(this.options.auth ? this.options.auth + '@' : '') +
this.host + ':' + this.options.port;
},
/**
Port number for this client.
@property port
@type {Number}
**/
get port() {
return this.options.port;
},
// -- Public Methods -------------------------------------------------------
/**
Performs multiple document create/index/delete operations in a single request.
See `Index.bulk()` for detailed usage instructions.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/bulk.html)
@example
client.bulk([
{create: {index: 'blog', type: 'post', id: '1', data: {
title: 'Hello',
body : 'Welcome to my stupid blog.'
}}},
{index: {index: 'blog', type: 'post', id: '2', data: {
title: 'Breaking news',
body : 'Today I ate a sandwich.'
}}},
{delete: {index: 'blog', type: 'post', id: '42'}}
], function (err, res) {
// ...
});
@method bulk
@param {Object[]} operations Array of operations to perform. See
`Index.bulk()` for a description of the expected object format.
@param {Object} [options] Options. See `Index.bulk()` for details.
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.res ElasticSearch response data.
@see Index.bulk
**/
bulk: wrapStaticIndexMethod('bulk'),
/**
Get the number of matches for a query
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/count.html)
@method count
@param {String} index Index name.
@param {String} type Type name.
@param {String} query Query to get the number of match for.
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.res ElasticSearch response data.
@static
@see Index.count
**/
count: wrapStaticIndexMethod('count'),
/**
Creates a new index.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/admin-indices-create-index.html)
@method createIndex
@param {String} name Name of the new index.
@param {Object} options Index options (see ElasticSearch docs for details).
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Index} callback.index Index instance for the newly created index.
@param {Object} callback.data ElasticSearch response data.
@see Index.create
**/
createIndex: wrapStaticIndexMethod('create'),
/**
Deletes a document from the specified index. See `Index.delete()` for the
complete list of supported options.
@method delete
@param {String} index Index name.
@param {String} type Type name.
@param {String} id Document id to delete.
@param {Object} [options] Delete options.
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.res ElasticSearch response.
@see Index.delete
**/
delete: wrapIndexMethod('delete'),
/**
Deletes the specified index or indices. If no indices are specified, **all**
indices on the server will be deleted.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/admin-indices-delete-index.html)
@method deleteIndex
@param {String|String[]} [names] Name of the index to delete, or an array of
names to delete multiple indices. If omitted, **all** indices will be
deleted.
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.data ElasticSearch response data.
@see Index.deleteIndex
**/
deleteIndex: wrapStaticIndexMethod('delete'),
/**
Gets a document from the specified index based on its id.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/get.html)
@method get
@param {String} name Index name.
@param {String} id Document id.
@param {Object} [options] Options.
@param {String|String[]} [options.fields] Document field name or array of
field names to retrieve. By default, all fields are retrieved.
@param {Boolean} [options.ignoreMissing=false] If `true`, an error will
not be returned if the index, type, or document do not exist. Instead,
a `null` document will be returned.
@param {String} [options.preference] Controls which shard replicas the
request should be executed on. By default, the operation will be
randomized between the shard replicas. See the ElasticSearch docs for
possible values.
@param {Boolean} [options.realtime=true] Whether or not to use realtime
GET. See the ElasticSearch docs for details.
@param {Boolean} [options.refresh=false] If `true`, the relevant shard
will be refreshed before the get operation to ensure that it's
searchable. This may cause heavy server load, so use with caution.
@param {String} [options.routing] Value that determines what shard this
document will be routed to. If not specified, a hash of the document's
id will be used. Note that an incorrectly routed get operation will
fail, so it's best to leave this alone unless you know your business.
@param {String} [options.type="_all"] If specified, the get operation will
be limited to documents of this type.
@param {Function} callback Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object|null} callback.doc Retrieved document or document fields,
or `null` if the document was not found and `options.ignoreMissing` is
`true`.
@param {Object} callback.res Full ElasticSearch response data.
@see Index.get
**/
get: wrapIndexMethod('get'),
/**
Gets an Index instance for interacting with the specified ElasticSearch
index.
@example
var client = new require('elastical').Client(),
tweets = client.getIndex('tweets');
@method getIndex
@param {String} name Index name.
@return {Index} Index instance.
@see Index
**/
getIndex: function (name) {
return this._indexCache[name] ||
(this._indexCache[name] = new Index(this, name));
},
/**
Gets mapping definitions for the specified type within the specified index.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/admin-indices-put-mapping.html)
@method getMapping
@param {String|String[]} names Index name or array of names.
@param {String} type Document type. If omitted, mappings for all type are returned.
@param {Function} callback Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.res ElasticSearch response data.
@static
@see Client.getMapping
**/
getMapping: wrapStaticIndexMethod('getMapping'),
/**
Adds a document to the specified index.
If the specified index doesn't exist, it will be created.
If a document already exists in that index with the specified _type_ and
_id_, it will be updated. Otherwise, a new document will be created.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/index_.html)
@example
client.index('blog', 'post', {
title : "Welcome to my stupid blog",
content: "This is the first and last time I'll post anything.",
tags : ['welcome', 'first post', 'last post'],
created: Date.now()
}, function (err, res) {
if (err) { throw err; }
console.log('Indexed a blog post');
});
@method index
@param {String} index Index name.
@param {String} type Document type.
@param {Object} doc Document data to index.
@param {Object} [options] Options.
@param {String} [options.consistency="quorum"] Write consistency to use
for this indexing operation. Permitted values are "one", "quorum" and
"all". See the ElasticSearch docs for details.
@param {Boolean} [options.create=false] Only create the document if it
doesn't already exist.
@param {String} [options.id] Document id. One will be automatically
generated if not specified.
@param {String} [options.parent] Parent document id.
@param {String} [options.percolate] Percolation query to check against
this document. See the ElasticSearch docs for details.
@param {Boolean} [options.refresh=false] If `true`, the document will be
made searchable immediately after it is indexed.
@param {String} [options.replication="sync"] Replication mode for this
indexing operation. Maybe be set to "sync" or "async".
@param {String} [options.routing] Value that determines what shard this
document will be routed to. If not specified, a hash of the document's
id will be used.
@param {String} [options.timeout="1m"] How long to wait for the primary
shard to become available to index this document before aborting. See
the ElasticSearch docs for details. This should be a value like "5m"
(5 minutes) or "15s" (15 seconds).
@param {Number} [options.version] Document version to create/update. If
this is set and `options.version_type` is not set,
`options.version_type` will automatically be set to "external".
@param {String} [options.version_type="internal"] Version type (either
"internal" or "external"). See the ElasticSearch docs for details.
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.res ElasticSearch response data.
@see Index.index
**/
index: wrapIndexMethod('index'),
/**
Checks whether the specified index or indices exist.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/admin-indices-indices-exists.html)
@method indexExists
@param {String|String[]} names Index name or array of names to check.
@param {Function} callback Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Boolean} callback.exists `true` if all specified indices exist,
`false` otherwise.
@see Index.exists
**/
indexExists: wrapStaticIndexMethod('exists'),
// http://www.elasticsearch.org/guide/reference/api/multi-get.html
multiGet: function () {
},
/**
Registers a mapping definition for the specified type within the specified
index or indices.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/admin-indices-put-mapping.html)
@method putMapping
@param {String|String[]} [names] Index name or array of names to define the
mapping within. If not specified, it will be defined in all indices.
@param {String} type Document type.
@param {Object} [mapping] Mapping definition. See the [ElasticSearch
docs](http://www.elasticsearch.org/guide/reference/mapping/) for
an overview.
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.res ElasticSearch response data.
@static
@see Client.putMapping
**/
putMapping: wrapStaticIndexMethod('putMapping'),
/**
Refreshes the specified index or indices.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/admin-indices-refresh.html)
@method refresh
@param {String|String[]} [names] Index name or array of names to refresh. If
not specified, all indices will be refreshed.
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.res ElasticSearch response data.
@see Index.refresh
**/
refresh: wrapStaticIndexMethod('refresh'),
/**
Searches for documents matching the given query.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/search/)
@example
var client = new require('elastical').Client();
client.search({query: 'pie'}, function (err, results) {
if (err) { throw err; }
console.log(results);
});
@method search
@param {Object} [options] Search options. Technically this argument is
optional, but you'll almost always want to provide at least a query.
@param {Object|String} [options.query] Search query. This can be a simple
string (in which case a "query_string" search will be performed) or a
full query object. See the [ElasticSearch Query DSL docs](http://www.elasticsearch.org/guide/reference/query-dsl/)
for details.
@param {Boolean} [options.explain=false] If `true`, results will include
an explanation of how the score was computed for each hit.
@param {Object} [options.facets] Facets to aggregate by. See the
[ElasticSearch facets docs](http://www.elasticsearch.org/guide/reference/api/search/facets/)
for details.
@param {String|String[]} [options.fields] Document field name or array of
field names to retrieve. By default, all fields are retrieved.
@param {Object} [options.filter] Result filter. See the [ElasticSearch
filtering docs](http://www.elasticsearch.org/guide/reference/api/search/filter.html)
for details.
@param {Number} [options.from=0] Return results starting at this offset.
@param {Object} [options.highlight] Result highlighting options. See the
[ElasticSearch highlighting docs](http://www.elasticsearch.org/guide/reference/api/search/highlighting.html)
for details.
@param {String|String[]} [options.index] Index name or array of index
names to search. By default all indices will be searched.
@param {Object} [options.indices_boost] Index boost options. See the
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/search/index-boost.html)
for details.
@param {Number} [options.min_score] If specified, documents with a score
lower than this will be filtered out.
@param {String} [options.preference] Controls which shard replicas the
request should be executed on. By default, the operation will be
randomized between the shard replicas. See the [ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/search/preference.html)
for possible values.
@param {String} [options.routing] Value that determines what shard this
search will be routed to.
@param {Object} [options.script_fields] Script expressions to evaluate for
specific fields. See the [ElasticSearch script fields docs](http://www.elasticsearch.org/guide/reference/api/search/script-fields.html)
for details.
@param {String} [options.scroll] Scroll timeout. If specified, nodes that
participate in this search will maintain resources for this query
until the timeout expires. See the [ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/search/scroll.html)
for details.
@param {String} [options.scroll_id] Scroll id to use for this request.
@param {String} [options.search_type] Search operation type to use. May be
one of "query_and_fetch", "query_then_fetch", "dfs_query_and_fetch",
"dfs_query_then_fetch", "count", or "scan". See the [ElasticSearch
docs](http://www.elasticsearch.org/guide/reference/api/search/search-type.html)
for details.
@param {Number} [options.size=10] Return this many results.
@param {Object} [options.sort] Sort options. See the [ElasticSearch sort
docs](http://www.elasticsearch.org/guide/reference/api/search/sort.html)
for details.
@param {String} [options.timeout] Timeout after which the search will be
aborted. Any hits that have been gathered before the timeout is
reached will be returned. Default is no timeout.
@param {Boolean} [options.track_scores=false] Whether or not to compute
scores when sorting by a field.
@param {String|String[]} [options.type] Type name or array of type names
to search. By default all types will be searched.
@param {Boolean} [options.version=false] If `true`, a version number will
be returned for each hit.
@param {Function} callback Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.results Search results.
@param {Object} callback.res Full ElasticSearch response data.
**/
search: function (options, callback) {
var query = [],
url = '',
hasOptions;
if (typeof options === 'function') {
callback = options;
options = {};
}
var useScrollingEndpoint = (options.scroll_id != null);
// Create a copy of options so we can modify it.
options = util.merge(options || {});
// Some options must be passed as query parameters. Find those options
// and move them into the query param array.
this._SEARCH_PARAMS.forEach(function (name) {
var value = options[name];
if (typeof value !== 'undefined') {
if (value === true || value === false) {
query.push(encode(name) + '=' + (value ? '1' : '0'));
} else {
query.push(encode(name) + '=' + encode(value));
}
delete options[name];
}
});
if (options.fields) {
options.fields = Array.isArray(options.fields) ? options.fields :
[options.fields];
}
if (options.index) {
url = '/' + encode(Array.isArray(options.index) ?
options.index.join(',') : options.index);
delete options.index;
}
// If a query is provided and it's a string, automatically turn it into
// a query_string query.
if (typeof options.query === 'string') {
options.query = {query_string: {query: options.query}};
}
if (options.type) {
if (!url) {
url = '/_all';
}
url += '/' + encode(Array.isArray(options.type) ?
options.type.join(',') : options.type);
delete options.type;
}
hasOptions = !!Object.keys(options).length;
url += '/_search';
if(useScrollingEndpoint){
url += '/scroll';
}
if (query.length) {
url += '?' + query.join('&');
}
this._request(url, {
method: hasOptions ? 'POST' : 'GET',
json : hasOptions ? options : {}
}, function (err, res) {
if (err) { return callback(err, null, res), undefined; }
callback(null, res.hits, res);
});
},
// TODO: percolate, delete by query, more like this
/**
Registers a percolator for the given index or modifies the existing percolator
if one with the name already exists
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/api/pecolator/)
@example
var put = {
"query" : {
"text" : {
"hashtags" : {
"query" : 'blah blah blah ',
"operator" : "or"
}
}
}
};
client.percolator('tweets', 'mypercolator', query, function (err, res) {
if (err) { throw err; }
console.log(results);
});
@method setPercolator
@param {String|String[]} index Index name or array of index
names to register the percolator.
@param {String} percolator The identifier string of the percolator.
This identifier is returned when a document matches
the query in the percolator, either through percolate operation or
through index opertation.
@param {Object|String} query Search query. Afull query object.
See the [ElasticSearch Query DSL docs](http://www.elasticsearch.org/guide/reference/query-dsl/)
for details.
@param {Function} callback Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.res Full ElasticSearch response data.
*/
setPercolator: wrapIndexMethod('setPercolator'),
/**
* Retrieve the percolator doc
*
* @example
*
* client.getPercolator('tweets', 'mypercolator', function (err, results) {
* if (err) { throw err; }
* console.log(results);
* });
*
* @param {String} index The index name to which the percolator is registered
* @param {String} percolator The name of the percolator
* @param {Function} callback Callback function.
* @param {Error|null} callback.err Error, or `null` on success.
* @param {Object} callback.doc Percolator document.
* @param {Object} callback.res Full ElasticSearch response data.
*/
getPercolator: wrapIndexMethod('getPercolator'),
/**
* Test if a given doc matches a percolator for
* the given index and document type
* @example
* client.perolate('tweets', 'tweet', {}, function(err, res){
* if(err){ throw err; }
* console.log(res);
* });
* @param {String} index The index name to which the document should be
* checked for matching percolators
* @param {String} type The type name of the document
* @param {Object} doc The document object which the registered percolators
* are matched against
* @param {Function} callback Callback function.
* @param {Error|null} callback.err Error, or `null` on success.
* @param {Object} callback.res Full ElasticSearch response data.
*/
percolate: wrapIndexMethod('percolate'),
/**
* Delete a registered percolator for the given index or indicies
* @example
* client.deletePercolator('tweets', 'mypercolator', function(err, res){
* if(err){ throw err;}
* console.log(res);
* });
* @param {String|String[]} index Index name or array of index names
* @param {String} percolator Name of the percolator to delete
* @param {Function} callback Callback function.
* @param {Error|null} callback.err Error, or `null` on success.
* @param {Object} callback.res Full ElasticSearch response data.
*/
deletePercolator: wrapIndexMethod('deletePercolator'),
/**
Registers a river with the cluster.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/river/)
@method putRiver
@param {String} name A name for this river.
@param {Object} config The river configuration.
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.res ElasticSearch response data.
@static
**/
putRiver: wrapIndexMethod('putRiver'),
/**
Gets river config from the cluster.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/river/)
@method getRiver
@param {Client} client Client instance.
@param {String} name A name for this river.
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.res ElasticSearch response data.
@static
**/
getRiver: wrapIndexMethod('getRiver'),
/**
Deletes a river config from the cluster.
[ElasticSearch docs](http://www.elasticsearch.org/guide/reference/river/)
@method deleteRiver
@param {Client} client Client instance.
@param {String} name A name for this river.
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object} callback.res ElasticSearch response data.
@static
**/
deleteRiver: wrapIndexMethod('deleteRiver'),
// -- Protected Methods ----------------------------------------------------
/**
Makes an HTTP request using the `request` module.
@method _request
@param {String} path Request path.
@param {Object} [options] Request options.
@param {Function} [callback] Callback function.
@param {Error|null} callback.err Error, or `null` on success.
@param {Object|Buffer|String} callback.body Response body (parsed as JSON
if possible).
@protected
**/
_request: function (path, options, callback) {
var url = this.baseUrl + path;
if (typeof options === 'function') {
callback = options;
options = {};
}
// Callback is optional.
callback || (callback = noop);
options = util.merge(options);
options.uri = url;
options.timeout || (options.timeout = this.options.timeout);
// Write executable curl commands to stderr for easier debugging when
// this client's curlDebug option is true.
if (this.options.curlDebug) {
curlDebug(options);
}
// Provide a testing hook to allow inspection of the request options
// without actually sending a request.
if (this._testHook) {
return this._testHook(null, options), undefined;
}
request(url, options, function (err, res, body) {
if (err) { return callback(err), undefined; }
// The request module will automatically try to parse the
// response as JSON if `options.json` is truthy and the response
// has an application/json content-type, but it currently fails
// on content-types with charset suffixes, so it can't be relied
// upon.
//
// See https://github.com/mikeal/request/commit/68c17f6c9a3d7217368b3b8bc61203e6a14eb4f0
if (typeof body === 'string' || body instanceof Buffer) {
body = body.toString('utf8');
try {
body = JSON.parse(body);
} catch (ex) {}
}
if (res.statusCode < 200 || res.statusCode > 299) {
callback(Error((body && body.error) || 'HTTP ' + res.statusCode),
body || {});
return;
}
callback(null, body || {});
return;
});
}
};
/**
Alias for index().
@method set
@see index
**/
Client.prototype.set = Client.prototype.index;
module.exports = Client;
// -- Private Functions --------------------------------------------------------
function noop() {}
function curlDebug(options) {
var command = 'curl -X' + (options.method || 'GET');
command += " '" + options.uri + "'";
if (options.body) {
command += " --data-binary '" + options.body + "'";
} else if (options.json) {
command += " -d '" + JSON.stringify(options.json, null, 2) + "'";
}
process.stderr.write(command + '\n');
}
function wrapIndexMethod(methodName) {
return function (indexName) {
var args = Array.prototype.slice.call(arguments, 1),
index = this.getIndex(indexName);
return index[methodName].apply(index, args);
};
}
function wrapStaticIndexMethod(methodName) {
return function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(this);
return Index[methodName].apply(Index, args);
}
}