-
Notifications
You must be signed in to change notification settings - Fork 127
/
elasticsearch.js
2172 lines (1912 loc) · 56.6 KB
/
elasticsearch.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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Kuzzle, a backend software, self-hostable and ready to use
* to power modern apps
*
* Copyright 2015-2018 Kuzzle
* mailto: support AT kuzzle.io
* website: http://kuzzle.io
*
* 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
*
* https://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.
*/
'use strict';
const
debug = require('../util/debug')('kuzzle:services:elasticsearch'),
_ = require('lodash'),
Bluebird = require('bluebird'),
ESWrapper = require('../util/esWrapper'),
didYouMean = require('../util/didYouMean'),
Service = require('./service'),
{ Client: ESClient } = require('@elastic/elasticsearch'),
ms = require('ms'),
{ assertIsObject } = require('../util/requestAssertions'),
errorsManager = require('../util/errors').wrap('services', 'storage'),
semver = require('semver'),
{ isPlainObject } = require('../util/safeObject');
const scrollCachePrefix = '_docscroll_';
const rootMappingProperties = ['properties', '_meta', 'dynamic', 'dynamic_templates'];
const childMappingProperties = ['type'];
// Used for collection emulation
const
HIDDEN_COLLECTION = '_kuzzle_keep',
INTERNAL_PREFIX = '%',
PUBLIC_PREFIX = '&',
NAME_SEPARATOR = '.',
FORBIDDEN_CHARS = `\\/*?"<>| \t\r\n,#:${NAME_SEPARATOR}${PUBLIC_PREFIX}${INTERNAL_PREFIX}`;
/**
* @param {Kuzzle} kuzzle kuzzle instance
* @param {Object} config Service configuration
* @param {String} scope - "internal" or "public" (default "public")
* @constructor
*/
class ElasticSearch extends Service {
/**
* Returns a new elasticsearch client instance
*
* @returns {Object}
*/
static buildClient (config) {
// Passed to Elasticsearch's client to make it use
// Bluebird instead of ES6 promises
const defer = function defer () {
let
resolve,
reject;
const promise = new Bluebird((res, rej) => {
resolve = res;
reject = rej;
});
return { resolve, reject, promise };
};
return new ESClient({ defer, ...config });
}
constructor(kuzzle, config, scope = 'public') {
super('elasticsearch', kuzzle, config);
this._scope = scope;
this._indexPrefix = scope === 'internal'
? INTERNAL_PREFIX
: PUBLIC_PREFIX;
this._client = null;
this._esWrapper = null;
this._esVersion = null;
}
get scope () {
return this._scope;
}
/**
* Initializes the elasticsearch client
*
* @override
* @returns {Promise}
*/
_initSequence () {
if (this._client) {
return Bluebird.resolve(this);
}
if (process.env.NODE_ENV === 'production' && this._config.commonMapping.dynamic === 'true') {
this._kuzzle.log.warn([
'Your dynamic mapping policy is set to \'true\' for new fields.',
'Elasticsearch will try to automatically infer mapping for new fields, and those cannot be changed afterward.',
'See the "services.storageEngine.commonMapping.dynamic" option in the kuzzlerc configuration file to change this value.'
].join('\n'));
}
this._client = ElasticSearch.buildClient(this._config.client);
this._esWrapper = new ESWrapper(this._client);
return this._client.info()
.then(({ body }) => {
this._esVersion = body.version;
if (this._esVersion && !semver.satisfies(this._esVersion.number, '>= 7.0.0')) {
errorsManager.throw('version_mismatch', this._esVersion.number);
}
});
}
/**
* Returns some basic information about this service
* @override
*
* @returns {Promise.<Object>} service informations
*/
info () {
const result = {
type: 'elasticsearch',
version: this._esVersion
};
return this._client.info()
.then(({ body }) => {
result.version = body.version.number;
result.lucene = body.version.lucene_version;
return this._client.cluster.health();
})
.then(({ body }) => {
result.status = body.status;
return this._client.cluster.stats({ human: true });
})
.then(({ body }) => {
result.spaceUsed = body.indices.store.size;
result.nodes = body.nodes;
return result;
})
.catch(error => this._esWrapper.reject(error));
}
/**
* Scrolls results from previous elasticsearch query
*
* @param {String} scrollId - Scroll identifier
* @param {Object} options - scrollTTL (default scrollTTL)
*
* @returns {Promise.<Object>} { scrollId, hits, aggregations, total }
*/
scroll (
scrollId,
{ scrollTTL=this._config.defaults.scrollTTL } = {})
{
const esRequest = {
scroll: scrollTTL,
scrollId
};
const cacheKey = scrollCachePrefix + this._kuzzle.constructor.hash(
esRequest.scrollId);
debug('Scroll: %o', esRequest);
return this._kuzzle.cacheEngine.internal.exists(cacheKey)
.then(exists => {
if (exists === 0) {
errorsManager.throw('unknown_scroll_id');
}
// ms(scroll) may return undefined if in microseconds or in nanoseconds
const ttl = ms(scrollTTL) || ms(this._config.defaults.scrollTTL);
return this._kuzzle.cacheEngine.internal.pexpire(cacheKey, ttl);
})
.then(() => this._client.scroll(esRequest))
.then(({ body }) => this._formatSearchResult(body))
.catch(error => this._esWrapper.reject(error));
}
/**
* Searches documents from elasticsearch with a query
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {Object} searchBody - Search request body (query, sort, etc.)
* @param {Object} options - from (undefined), size (undefined), scroll (undefined)
*
* @returns {Promise.<Object>} { scrollId, hits, aggregations, total }
*/
search (
index,
collection,
searchBody,
{ from, size, scroll } = {})
{
const esRequest = {
index: this._getESIndex(index, collection),
body: this._avoidEmptyClause(searchBody),
from,
size,
scroll
};
debug('Search: %o', esRequest);
return this._client.search(esRequest)
.then(({ body }) => {
if (body._scroll_id) {
const
// ms(scroll) may return undefined if in microseconds or in nanoseconds
ttl = esRequest.scroll && ms(esRequest.scroll)
|| ms(this._config.defaults.scrollTTL),
key = scrollCachePrefix + this._kuzzle.constructor.hash(
body._scroll_id
);
return this._kuzzle.cacheEngine.internal.psetex(key, ttl, 0)
.then(() => this._formatSearchResult(body));
}
return this._formatSearchResult(body);
})
.catch(error => this._esWrapper.reject(error));
}
_formatSearchResult (body) {
const hits = [];
for (let i = 0; i < body.hits.hits.length; i++) {
const hit = body.hits.hits[i];
hits.push({
_id: hit._id,
_score: hit._score,
_source: hit._source,
highlight: hit.highlight
});
}
return {
hits,
scrollId: body._scroll_id,
aggregations: body.aggregations,
total: body.hits.total.value
};
}
/**
* Gets the document with given ID
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {String} id - Document ID
*
* @returns {Promise.<Object>} { _id, _version, _source }
*/
get (index, collection, id) {
const esRequest = {
index: this._getESIndex(index, collection),
id
};
// Just in case the user make a GET on url /mainindex/test/_search
// Without this test we return something weird: a result.hits.hits with all
// document without filter because the body is empty in HTTP by default
if (esRequest.id === '_search') {
return errorsManager.reject('search_as_an_id');
}
debug('Get document: %o', esRequest);
return this._client.get(esRequest)
.then(({ body }) => ({
_id: body._id,
_version: body._version,
_source: body._source
}))
.catch(error => this._esWrapper.reject(error));
}
/**
* Returns the list of documents matching the ids given in the body param
* NB: Due to internal Kuzzle mechanism, can only be called on a single index/collection,
* using the body { ids: [.. } syntax.
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {Array.<String>} ids - Document IDs
*
* @returns {Promise.<Object>} { items: [ _id, _source, _version ], errors }
*/
mGet (index, collection, ids) {
if (ids.length === 0) {
return Bluebird.resolve({ item: [], errors: [] });
}
const
esIndex = this._getESIndex(index, collection),
esRequest = {
body: { docs: [] }
};
for (const _id of ids) {
esRequest.body.docs.push({
_index: esIndex,
_id
});
}
debug('Multi-get documents: %o', esRequest);
return this._client.mget(esRequest)
.then(({ body }) => {
const
errors = [],
items = [];
for (const doc of body.docs) {
if (doc.found) {
items.push({
_id: doc._id,
_source: doc._source,
_version: doc._version
});
}
else {
errors.push(doc._id);
}
}
return {
items,
errors
};
})
.catch(error => this._esWrapper.reject(error));
}
/**
* Counts how many documents match the filter given in body
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {Object} searchBody - Search request body (query, sort, etc.)
*
* @returns {Promise.<Number>} count
*/
count (index, collection, searchBody = {}) {
const esRequest = {
index: this._getESIndex(index, collection),
body: this._avoidEmptyClause(searchBody)
};
debug('Count: %o', esRequest);
return this._client.count(esRequest)
.then(({ body }) => body.count)
.catch(error => this._esWrapper.reject(error));
}
/**
* Sends the new document to elasticsearch
* Cleans data to match elasticsearch specifications
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {Object} content - Document content
* @param {Object} options - id (undefined), refresh (undefined), userId (null)
*
* @returns {Promise.<Object>} { _id, _version, _source }
*/
async create (
index,
collection,
content,
{ id, refresh, userId=null } = {})
{
assertIsObject(content);
const esRequest = {
index: this._getESIndex(index, collection),
body: content,
op_type: id ? 'create' : 'index',
id,
refresh
};
assertNoRouting(esRequest);
assertWellFormedRefresh(esRequest);
// Add metadata
esRequest.body._kuzzle_info = {
author: getUserId(userId),
createdAt: Date.now(),
updatedAt: null,
updater: null
};
debug('Create document: %o', esRequest);
try {
const { body } = await this._client.index(esRequest);
return {
_id: body._id,
_version: body._version,
_source: esRequest.body
};
}
catch (error) {
return this._esWrapper.reject(error);
}
}
/**
* Creates a new document to ElasticSearch, or replace it if it already exist
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {String} id - Document id
* @param {Object} content - Document content
* @param {Object} options - refresh (undefined), userId (null), injectKuzzleMeta (true)
*
* @returns {Promise.<Object>} { _id, _version, _source, created }
*/
createOrReplace (
index,
collection,
id,
content,
{ refresh, userId=null, injectKuzzleMeta=true } = {})
{
const esRequest = {
index: this._getESIndex(index, collection),
body: content,
id,
refresh
};
assertNoRouting(esRequest);
assertWellFormedRefresh(esRequest);
// Add metadata
if (injectKuzzleMeta) {
esRequest.body._kuzzle_info = {
author: getUserId(userId),
createdAt: Date.now(),
updatedAt: Date.now(),
updater: getUserId(userId)
};
}
debug('Create or replace document: %o', esRequest);
return this._client.index(esRequest)
.then(({ body }) => ({
_id: body._id,
_version: body._version,
_source: esRequest.body,
created: body.created // Needed by the notifier
}))
.catch(error => this._esWrapper.reject(error));
}
/**
* Sends the partial document to elasticsearch with the id to update
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {String} id - Document id
* @param {Object} content - Updated content
* @param {Object} options - refresh (undefined), userId (null), retryOnConflict (0)
*
* @returns {Promise.<Object>} { _id, _version }
*/
update (
index,
collection,
id,
content,
{ refresh, userId=null, retryOnConflict=this._config.defaults.onUpdateConflictRetries } = {})
{
const esRequest = {
index: this._getESIndex(index, collection),
body: { doc: content },
id,
refresh,
retryOnConflict
};
assertNoRouting(esRequest);
assertWellFormedRefresh(esRequest);
// Add metadata
esRequest.body.doc._kuzzle_info = {
updatedAt: Date.now(),
updater: getUserId(userId)
};
debug('Update document: %o', esRequest);
return this._client.update(esRequest)
.then(({ body }) => ({
_id: body._id,
_version: body._version
}))
.catch(error => this._esWrapper.reject(error));
}
/**
* Replaces a document to ElasticSearch
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {String} id - Document id
* @param {Object} content - Document content
* @param {Object} options - refresh (undefined), userId (null)
*
* @returns {Promise.<Object>} { _id, _version, _source }
*/
replace (
index,
collection,
id,
content,
{ refresh, userId=null } = {})
{
const
esIndex = this._getESIndex(index, collection),
esRequest = {
index: esIndex,
body: content,
id,
refresh
};
assertNoRouting(esRequest);
assertWellFormedRefresh(esRequest);
// Add metadata
esRequest.body._kuzzle_info = {
author: getUserId(userId),
createdAt: Date.now(),
updatedAt: Date.now(),
updater: getUserId(userId)
};
return this._client.exists({ index: esIndex, id })
.then(({ body: exists }) => {
if (! exists) {
errorsManager.throw('not_found', id);
}
debug('Replace document: %o', esRequest);
return this._client.index(esRequest);
})
.then(({ body }) => ({
_id: id,
_version: body._version,
_source: esRequest.body
}))
.catch(error => this._esWrapper.reject(error));
}
/**
* Sends to elasticsearch the document id to delete
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {String} id - Document id
* @param {Object} options - refresh (undefined)
*
* @returns {Promise}
*/
delete (
index,
collection,
id,
{ refresh } = {})
{
const esRequest = {
index: this._getESIndex(index, collection),
id,
refresh
};
assertWellFormedRefresh(esRequest);
debug('Delete document: %o', esRequest);
return this._client.delete(esRequest)
.then(() => null)
.catch(error => this._esWrapper.reject(error));
}
/**
* Deletes all documents matching the provided filters
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {Object} query - Query to match documents
* @param {Object} options - from (undefined), size (undefined), refresh (undefined)
*
* @returns {Promise.<Object>} { documents, total, deleted, failures: [ _shardId, reason ] }
*/
deleteByQuery (
index,
collection,
query,
{ refresh, from, size } = {})
{
const esRequest = {
index: this._getESIndex(index, collection),
body: this._avoidEmptyClause({ query }),
scroll: '5s',
from,
size
};
if (!isPlainObject(query)) {
return errorsManager.reject('missing_argument', 'body.query');
}
let documents;
esRequest.refresh = refresh === 'wait_for' ? true : refresh;
return this.refreshCollection(index, collection)
.then(() => this._getAllDocumentsFromQuery(esRequest))
.then(_documents => {
documents = _documents;
debug('Delete by query: %o', esRequest);
return this._client.deleteByQuery(esRequest);
})
.then(({ body }) => ({
documents,
total: body.total,
deleted: body.deleted,
failures:
body.failures.map(({ shardId, reason }) => ({
shardId,
reason
}))
}))
.catch(error => this._esWrapper.reject(error));
}
/**
* Execute the callback with a batch of documents of specified size until all
* documents matched by the query have been processed.
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {Object} query - Query to match documents
* @param {Function} callback - callback that will be called with the "hits" array
* @param {Object} options - size (10), scrollTTL ('5s')
*
* @returns {Promise.<any[]>} Array of results returned by the callback
*/
batchExecute (
index,
collection,
query,
callback,
{ size=10, scrollTTl= '5s' } = {})
{
const esRequest = {
index: this._getESIndex(index, collection),
body: this._avoidEmptyClause({ query }),
scroll: scrollTTl,
from: 0,
size
};
if (! _.isPlainObject(query)) {
return errorsManager.reject('missing_argument', 'body.query');
}
const
client = this._client,
results = [];
let processed = 0;
return new Bluebird((resolve, reject) => {
this._client.search(
esRequest,
async function getMoreUntilDone(error, { body: { hits, _scroll_id } }) {
if (error) {
return reject(error);
}
const ret = callback(hits.hits);
if (ret && typeof ret.then === 'function') {
results.push(await ret);
}
else {
results.push(ret);
}
processed += hits.hits.length;
if (hits.total.value !== processed) {
client.scroll({
scrollId: _scroll_id,
scroll: esRequest.scroll
}, getMoreUntilDone);
}
else {
resolve(results);
}
});
});
}
/**
* Creates a new index.
*
* This methods creates an hidden collection in the provided index to be
* able to list it.
* This methods resolves if the index name does not already exists either as
* internal or public index.
*
* @param {String} index - Index name
*
* @returns {Promise}
*/
async createIndex (index) {
this._assertValidIndexAndCollection(index);
let body;
try {
({ body } = await this._client.cat.indices({ format: 'json' })); // NOSONAR
}
catch (e) {
return this._esWrapper.reject(e);
}
const esIndexes = body.map(({ index: name }) => name);
for (const esIndex of esIndexes) {
const indexName = this._extractIndex(esIndex);
if (index === indexName) {
const indexType = esIndex[0] === INTERNAL_PREFIX
? 'private'
: 'public';
errorsManager.throw('index_already_exists', indexType, index);
}
}
const esRequest = {
index: this._getESIndex(index, HIDDEN_COLLECTION),
body: {}
};
try {
await this._client.indices.create(esRequest);
}
catch (e) {
return this._esWrapper.reject(e);
}
return null;
}
/**
* Creates an empty collection. Mapping will be applied if supplied.
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {Object} mappings - Collection mappings in ES format
*
* @returns {Promise}
*/
async createCollection (index, collection, mappings = {}) {
this._assertValidIndexAndCollection(index, collection);
const esRequest = {
index: this._getESIndex(index, collection),
body: {}
};
if (collection === HIDDEN_COLLECTION) {
errorsManager.throw('collection_reserved', HIDDEN_COLLECTION);
}
const exists = await this.collectionExists(index, collection);
if (exists) {
return this.updateMapping(index, collection, mappings);
}
this._checkMappings(mappings);
esRequest.body.mappings = {
dynamic: mappings.dynamic || this._config.commonMapping.dynamic,
_meta: mappings._meta || this._config.commonMapping._meta,
properties: _.merge(
mappings.properties,
this._config.commonMapping.properties)
};
try {
await this._client.indices.create(esRequest);
}
catch (error) {
if (_.get(error, 'meta.body.error.type') === 'resource_already_exists_exception') {
// race condition: the index has been created between the "exists"
// check above and this "create" attempt
return null;
}
return this._esWrapper.reject(error);
}
return null;
}
/**
* Retrieves mapping definition for index/type
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {Object} options - includeKuzzleMeta (false)
*
* @return {Promise.<Object>} { dynamic, _meta, properties }
*/
getMapping (index, collection, { includeKuzzleMeta=false } = {}) {
const
esIndex = this._getESIndex(index, collection),
esRequest = {
index: esIndex
};
debug('Get mapping: %o', esRequest);
return this._client.indices.getMapping(esRequest)
.then(({ body }) => {
const properties = includeKuzzleMeta
? body[esIndex].mappings.properties
: _.omit(body[esIndex].mappings.properties, '_kuzzle_info');
return {
dynamic: body[esIndex].mappings.dynamic,
_meta: body[esIndex].mappings._meta,
properties
};
})
.catch(error => this._esWrapper.reject(error));
}
/**
* Adds a mapping definition to a specific type
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {Object} mappings - Collection mappings in ES format
*
* @return {Promise.<Object>} { dynamic, _meta, properties }
*/
updateMapping (index, collection, mappings = {}) {
const esRequest = {
index: this._getESIndex(index, collection)
};
let fullProperties;
return this.getMapping(index, collection, true)
.then(collectionMappings => {
this._checkMappings(mappings);
esRequest.body = {
dynamic: mappings.dynamic || collectionMappings.dynamic,
_meta: mappings._meta || collectionMappings._meta,
properties: mappings.properties
};
fullProperties = _.merge(collectionMappings.properties, mappings.properties);
debug('Update mapping: %o', esRequest);
return this._client.indices.putMapping(esRequest);
})
.then(() => ({
dynamic: esRequest.body.dynamic,
_meta: esRequest.body._meta,
properties: fullProperties
}))
.catch(error => this._esWrapper.reject(error));
}
/**
* Empties the content of a collection. Keep the existing mapping.
*
* @param {String} index - Index name
* @param {String} collection - Collection name
*
* @returns {Promise}
*/
truncateCollection (index, collection) {
let mappings;
const esRequest = {
index: this._getESIndex(index, collection)
};
return this.getMapping(index, collection)
.then(collectionMappings => {
mappings = collectionMappings;
return this._client.indices.delete(esRequest);
})
.then(() => this._client.indices.create({ ...esRequest, body: { mappings } }))
.then(() => null)
.catch(error => this._esWrapper.reject(error));
}
/**
* Runs several action and document
*
* @param {String} index - Index name
* @param {String} collection - Collection name
* @param {Array.<Object>} documents - Documents to import
* @param {Object} options - timeout (undefined), refresh (undefined), userId (null)
*
* @returns {Promise.<Object>} { items, errors }
*/
import (
index,
collection,
documents,
{ refresh, timeout, userId=null } = {})
{
const
esIndex = this._getESIndex(index, collection),
actionNames = ['index', 'create', 'update', 'delete'],
dateNow = Date.now(),
esRequest = {
body: documents,
refresh,
timeout
},
kuzzleMeta = {
created: {
author: getUserId(userId),
createdAt: dateNow,
updatedAt: null,
updater: null
},
updated: {
updater: getUserId(userId),
updatedAt: dateNow
}
};
assertWellFormedRefresh(esRequest);
let
actionCount = 0,
lastAction; // NOSONAR
/**
* @warning Critical code section
*
* bulk body can contain more than 10K elements
*/
for (let i = 0; i < esRequest.body.length; i++) {
const
item = esRequest.body[i],
action = Object.keys(item)[0];
if (actionNames.indexOf(action) !== -1) {
lastAction = action;
actionCount++;
item[action]._index = esIndex;