kuzzle 2.60.1 → 2.61.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/lib/cluster/idCardHandler.d.ts +11 -1
- package/dist/lib/cluster/idCardHandler.js +10 -2
- package/dist/lib/cluster/node.d.ts +14 -0
- package/dist/lib/cluster/node.js +19 -0
- package/dist/lib/config/index.js +43 -8
- package/dist/lib/core/backend/backendStorage.js +4 -6
- package/dist/lib/core/plugin/pluginContext.js +2 -2
- package/dist/lib/core/storage/clientAdapter.d.ts +13 -10
- package/dist/lib/core/storage/clientAdapter.js +112 -60
- package/dist/lib/core/storage/conformance/capabilityCases.d.ts +3 -0
- package/dist/lib/core/storage/conformance/capabilityCases.js +121 -0
- package/dist/lib/core/storage/conformance/conformanceContext.d.ts +33 -0
- package/dist/lib/core/storage/conformance/conformanceContext.js +97 -0
- package/dist/lib/core/storage/conformance/conformanceEnvironment.d.ts +7 -0
- package/dist/lib/core/storage/conformance/conformanceEnvironment.js +136 -0
- package/dist/lib/core/storage/conformance/coreCases.d.ts +3 -0
- package/dist/lib/core/storage/conformance/coreCases.js +381 -0
- package/dist/lib/core/storage/conformance/storageDriverConformance.d.ts +53 -0
- package/dist/lib/core/storage/conformance/storageDriverConformance.js +89 -0
- package/dist/lib/core/storage/indexCache.d.ts +26 -2
- package/dist/lib/core/storage/indexCache.js +100 -2
- package/dist/lib/core/storage/storageDriverLoader.d.ts +41 -0
- package/dist/lib/core/storage/storageDriverLoader.js +276 -0
- package/dist/lib/core/storage/storageEngine.js +9 -1
- package/dist/lib/core/storage/storageError.d.ts +15 -0
- package/dist/lib/core/storage/storageError.js +36 -0
- package/dist/lib/kerror/codes/1-services.json +35 -0
- package/dist/lib/kerror/codes/8-cluster.json +6 -0
- package/dist/lib/service/storage/builtInDrivers.d.ts +6 -0
- package/dist/lib/service/storage/builtInDrivers.js +103 -0
- package/dist/lib/service/storage/storageService.d.ts +13 -0
- package/dist/lib/service/storage/storageService.js +44 -0
- package/dist/lib/types/config/KuzzleConfiguration.d.ts +8 -0
- package/dist/lib/types/config/storageEngine/StorageEngineElasticsearchConfiguration.d.ts +13 -1
- package/dist/lib/types/index.d.ts +1 -0
- package/dist/lib/types/index.js +1 -0
- package/dist/lib/types/storage/StorageDriver.d.ts +306 -0
- package/dist/lib/types/storage/StorageDriver.js +41 -0
- package/dist/package.json +4 -1
- package/package.json +4 -1
- package/dist/lib/service/storage/7/elasticsearch.d.ts +0 -1054
- package/dist/lib/service/storage/7/elasticsearch.js +0 -3063
- package/dist/lib/service/storage/7/esWrapper.d.ts +0 -36
- package/dist/lib/service/storage/7/esWrapper.js +0 -295
- package/dist/lib/service/storage/8/elasticsearch.d.ts +0 -1047
- package/dist/lib/service/storage/8/elasticsearch.js +0 -3096
- package/dist/lib/service/storage/8/esWrapper.d.ts +0 -36
- package/dist/lib/service/storage/8/esWrapper.js +0 -295
- package/dist/lib/service/storage/Elasticsearch.d.ts +0 -16
- package/dist/lib/service/storage/Elasticsearch.js +0 -48
|
@@ -1,3096 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
/*
|
|
3
|
-
* Kuzzle, a backend software, self-hostable and ready to use
|
|
4
|
-
* to power modern apps
|
|
5
|
-
*
|
|
6
|
-
* Copyright 2015-2022 Kuzzle
|
|
7
|
-
* mailto: support AT kuzzle.io
|
|
8
|
-
* website: http://kuzzle.io
|
|
9
|
-
*
|
|
10
|
-
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
11
|
-
* you may not use this file except in compliance with the License.
|
|
12
|
-
* You may obtain a copy of the License at
|
|
13
|
-
*
|
|
14
|
-
* https://www.apache.org/licenses/LICENSE-2.0
|
|
15
|
-
*
|
|
16
|
-
* Unless required by applicable law or agreed to in writing, software
|
|
17
|
-
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
18
|
-
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
19
|
-
* See the License for the specific language governing permissions and
|
|
20
|
-
* limitations under the License.
|
|
21
|
-
*/
|
|
22
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
23
|
-
if (k2 === undefined) k2 = k;
|
|
24
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
25
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
26
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
27
|
-
}
|
|
28
|
-
Object.defineProperty(o, k2, desc);
|
|
29
|
-
}) : (function(o, m, k, k2) {
|
|
30
|
-
if (k2 === undefined) k2 = k;
|
|
31
|
-
o[k2] = m[k];
|
|
32
|
-
}));
|
|
33
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
34
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
35
|
-
}) : function(o, v) {
|
|
36
|
-
o["default"] = v;
|
|
37
|
-
});
|
|
38
|
-
var __importStar = (this && this.__importStar) || (function () {
|
|
39
|
-
var ownKeys = function(o) {
|
|
40
|
-
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
41
|
-
var ar = [];
|
|
42
|
-
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
43
|
-
return ar;
|
|
44
|
-
};
|
|
45
|
-
return ownKeys(o);
|
|
46
|
-
};
|
|
47
|
-
return function (mod) {
|
|
48
|
-
if (mod && mod.__esModule) return mod;
|
|
49
|
-
var result = {};
|
|
50
|
-
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
51
|
-
__setModuleDefault(result, mod);
|
|
52
|
-
return result;
|
|
53
|
-
};
|
|
54
|
-
})();
|
|
55
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
56
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
57
|
-
};
|
|
58
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
59
|
-
exports.ES8 = void 0;
|
|
60
|
-
const lodash_1 = __importDefault(require("lodash"));
|
|
61
|
-
const sdk_es8_1 = require("sdk-es8");
|
|
62
|
-
const assert_1 = __importDefault(require("assert"));
|
|
63
|
-
const bluebird_1 = __importDefault(require("bluebird"));
|
|
64
|
-
const ms_1 = __importDefault(require("ms"));
|
|
65
|
-
const semver_1 = __importDefault(require("semver"));
|
|
66
|
-
const storeScopeEnum_1 = require("../../../core/storage/storeScopeEnum");
|
|
67
|
-
const kerror = __importStar(require("../../../kerror"));
|
|
68
|
-
const didYouMean_1 = __importDefault(require("../../../util/didYouMean"));
|
|
69
|
-
const extractFields_1 = __importDefault(require("../../../util/extractFields"));
|
|
70
|
-
const distributedLock_1 = require("../../../util/distributedLock");
|
|
71
|
-
const name_generator_1 = require("../../../util/name-generator");
|
|
72
|
-
const requestAssertions_1 = require("../../../util/requestAssertions");
|
|
73
|
-
const safeObject_1 = require("../../../util/safeObject");
|
|
74
|
-
const queryTranslator_1 = require("../commons/queryTranslator");
|
|
75
|
-
const esWrapper_1 = __importDefault(require("./esWrapper"));
|
|
76
|
-
const SCROLL_CACHE_PREFIX = "_docscroll_";
|
|
77
|
-
const ROOT_MAPPING_PROPERTIES = [
|
|
78
|
-
"properties",
|
|
79
|
-
"_meta",
|
|
80
|
-
"dynamic",
|
|
81
|
-
"dynamic_templates",
|
|
82
|
-
];
|
|
83
|
-
const CHILD_MAPPING_PROPERTIES = ["type"];
|
|
84
|
-
// Used for collection emulation
|
|
85
|
-
const HIDDEN_COLLECTION = "_kuzzle_keep";
|
|
86
|
-
// The hidden collection locks wait for as long as it takes, as the `Mutex`
|
|
87
|
-
// they replace did: they guard a collection creation, which must not fail
|
|
88
|
-
// only because another request on the same index got there first. The lock
|
|
89
|
-
// is refreshed while held, so a live holder is never overtaken; a crashed
|
|
90
|
-
// one leaves it for at most `ttl` (30 s).
|
|
91
|
-
const HIDDEN_COLLECTION_LOCK = { retryAttempts: Number.POSITIVE_INFINITY };
|
|
92
|
-
// How long `waitForCollectionShards` lets Elasticsearch wait for a
|
|
93
|
-
// collection's primary shards, which is also Elasticsearch's own default
|
|
94
|
-
const COLLECTION_SHARDS_TIMEOUT = "30s";
|
|
95
|
-
const ALIAS_PREFIX = "@"; // @todo next major release: Add ALIAS_PREFIX in FORBIDDEN_CHARS
|
|
96
|
-
const PRIVATE_PREFIX = "%";
|
|
97
|
-
const PUBLIC_PREFIX = "&";
|
|
98
|
-
const INDEX_PREFIX_POSITION_IN_INDICE = 0;
|
|
99
|
-
const INDEX_PREFIX_POSITION_IN_ALIAS = 1;
|
|
100
|
-
const NAME_SEPARATOR = ".";
|
|
101
|
-
/**
|
|
102
|
-
* Marks an indice the core must leave alone: neither given a missing alias
|
|
103
|
-
* (`generateMissingAliases`) nor counted in the storage stats. Set by tools
|
|
104
|
-
* building a collection's next indice beside it (e.g. a mapping migration).
|
|
105
|
-
* It sits outside the `@&` / `@%` alias convention, so every alias reader
|
|
106
|
-
* already ignores it.
|
|
107
|
-
*/
|
|
108
|
-
const UNMANAGED_INDICE_ALIAS = "kuzzle-unmanaged";
|
|
109
|
-
const FORBIDDEN_CHARS = `\\/*?"<>| \t\r\n,+#:${NAME_SEPARATOR}${PUBLIC_PREFIX}${PRIVATE_PREFIX}`;
|
|
110
|
-
const DYNAMIC_PROPERTY_VALUES = ["true", "false", "strict"];
|
|
111
|
-
// used to check whether we need to wait for ES to initialize or not
|
|
112
|
-
var esStateEnum;
|
|
113
|
-
(function (esStateEnum) {
|
|
114
|
-
esStateEnum[esStateEnum["AWAITING"] = 1] = "AWAITING";
|
|
115
|
-
esStateEnum[esStateEnum["NONE"] = 2] = "NONE";
|
|
116
|
-
esStateEnum[esStateEnum["OK"] = 3] = "OK";
|
|
117
|
-
})(esStateEnum || (esStateEnum = {}));
|
|
118
|
-
let esState = esStateEnum.NONE;
|
|
119
|
-
/**
|
|
120
|
-
* @param {Kuzzle} kuzzle kuzzle instance
|
|
121
|
-
* @param {Object} config Service configuration
|
|
122
|
-
* @param {storeScopeEnum} scope
|
|
123
|
-
* @constructor
|
|
124
|
-
*/
|
|
125
|
-
class ES8 {
|
|
126
|
-
constructor(config, scope = storeScopeEnum_1.storeScopeEnum.PUBLIC) {
|
|
127
|
-
this.logger = global.kuzzle.log.child("service:storage:elasticsearch:8");
|
|
128
|
-
this._config = config;
|
|
129
|
-
this._scope = scope;
|
|
130
|
-
this._indexPrefix =
|
|
131
|
-
scope === storeScopeEnum_1.storeScopeEnum.PRIVATE ? PRIVATE_PREFIX : PUBLIC_PREFIX;
|
|
132
|
-
this._esVersion = null;
|
|
133
|
-
this._translator = new queryTranslator_1.QueryTranslator();
|
|
134
|
-
// Allowed root key of a search query
|
|
135
|
-
this.searchBodyKeys = [
|
|
136
|
-
"aggregations",
|
|
137
|
-
"aggs",
|
|
138
|
-
"collapse",
|
|
139
|
-
"explain",
|
|
140
|
-
"fields",
|
|
141
|
-
"from",
|
|
142
|
-
"highlight",
|
|
143
|
-
"post_filter",
|
|
144
|
-
"query",
|
|
145
|
-
"search_after",
|
|
146
|
-
"search_timeout",
|
|
147
|
-
"size",
|
|
148
|
-
"sort",
|
|
149
|
-
"suggest",
|
|
150
|
-
"_name",
|
|
151
|
-
"_source",
|
|
152
|
-
"_source_excludes",
|
|
153
|
-
"_source_includes",
|
|
154
|
-
];
|
|
155
|
-
/**
|
|
156
|
-
* Only allow stored-scripts in queries
|
|
157
|
-
*/
|
|
158
|
-
this.scriptKeys = ["script", "_script"];
|
|
159
|
-
this.scriptAllowedArgs = ["id", "params"];
|
|
160
|
-
this.maxScrollDuration = this._loadMsConfig("maxScrollDuration");
|
|
161
|
-
this.scrollTTL = this._loadMsConfig("defaults.scrollTTL");
|
|
162
|
-
}
|
|
163
|
-
get scope() {
|
|
164
|
-
return this._scope;
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* Initializes the elasticsearch client
|
|
168
|
-
*
|
|
169
|
-
* @override
|
|
170
|
-
* @returns {Promise}
|
|
171
|
-
*/
|
|
172
|
-
async _initSequence() {
|
|
173
|
-
if (this._client) {
|
|
174
|
-
return;
|
|
175
|
-
}
|
|
176
|
-
if (global.NODE_ENV !== "development" &&
|
|
177
|
-
this._config.commonMapping.dynamic === "true") {
|
|
178
|
-
this.logger.warn([
|
|
179
|
-
"Your dynamic mapping policy is set to 'true' for new fields.",
|
|
180
|
-
"Elasticsearch will try to automatically infer mapping for new fields, and those cannot be changed afterward.",
|
|
181
|
-
'See the "services.storageEngine.commonMapping.dynamic" option in the kuzzlerc configuration file to change this value.',
|
|
182
|
-
].join("\n"));
|
|
183
|
-
}
|
|
184
|
-
this._client = new sdk_es8_1.Client(this._config.client);
|
|
185
|
-
await this.waitForElasticsearch();
|
|
186
|
-
this._esWrapper = new esWrapper_1.default(this._client);
|
|
187
|
-
const { version } = await this._client.info();
|
|
188
|
-
if (version) {
|
|
189
|
-
const coerced = semver_1.default.coerce(version.number);
|
|
190
|
-
if (coerced === null || !semver_1.default.satisfies(coerced, ">=8.0.0")) {
|
|
191
|
-
throw kerror.get("services", "storage", "version_mismatch", version.number);
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
this._esVersion = version;
|
|
195
|
-
}
|
|
196
|
-
/**
|
|
197
|
-
* Translate Koncorde filters to Elasticsearch query
|
|
198
|
-
*
|
|
199
|
-
* @param {Object} filters - Set of valid Koncorde filters
|
|
200
|
-
* @returns {Object} Equivalent Elasticsearch query
|
|
201
|
-
*/
|
|
202
|
-
translateKoncordeFilters(filters) {
|
|
203
|
-
return this._translator.translate(filters);
|
|
204
|
-
}
|
|
205
|
-
/**
|
|
206
|
-
* Returns some basic information about this service
|
|
207
|
-
* @override
|
|
208
|
-
*
|
|
209
|
-
* @returns {Promise.<InfoResult>} service informations
|
|
210
|
-
*/
|
|
211
|
-
async info() {
|
|
212
|
-
const result = {
|
|
213
|
-
type: "elasticsearch",
|
|
214
|
-
version: this._esVersion?.number ?? "",
|
|
215
|
-
};
|
|
216
|
-
try {
|
|
217
|
-
const info = await this._client.info();
|
|
218
|
-
result.version = info.version.number;
|
|
219
|
-
result.lucene = info.version.lucene_version;
|
|
220
|
-
const health = await this._client.cluster.health();
|
|
221
|
-
result.status = health.status;
|
|
222
|
-
const stats = await this._client.cluster.stats({ human: true });
|
|
223
|
-
result.spaceUsed = stats.indices.store.size;
|
|
224
|
-
result.nodes = stats.nodes;
|
|
225
|
-
return result;
|
|
226
|
-
}
|
|
227
|
-
catch (error) {
|
|
228
|
-
return this._esWrapper.reject(error);
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
/**
|
|
232
|
-
* Returns detailed multi-level storage stats data
|
|
233
|
-
*
|
|
234
|
-
* @returns {Promise.<Object>}
|
|
235
|
-
*/
|
|
236
|
-
async stats() {
|
|
237
|
-
const esRequest = {
|
|
238
|
-
metric: ["docs", "store"],
|
|
239
|
-
};
|
|
240
|
-
const stats = await this._client.indices.stats(esRequest);
|
|
241
|
-
const unmanaged = await this._listUnmanagedIndices();
|
|
242
|
-
const indexes = {};
|
|
243
|
-
let size = 0;
|
|
244
|
-
for (const [indice, indiceInfo] of Object.entries(stats.indices ?? {})) {
|
|
245
|
-
// Ignore non-Kuzzle indices, and the ones Kuzzle must leave alone
|
|
246
|
-
if ((!indice.startsWith(PRIVATE_PREFIX) &&
|
|
247
|
-
!indice.startsWith(PUBLIC_PREFIX)) ||
|
|
248
|
-
unmanaged.has(indice)) {
|
|
249
|
-
continue;
|
|
250
|
-
}
|
|
251
|
-
const aliases = await this._getAliasFromIndice(indice);
|
|
252
|
-
const alias = aliases[0];
|
|
253
|
-
const indexName = this._extractIndex(alias);
|
|
254
|
-
const collectionName = this._extractCollection(alias);
|
|
255
|
-
if (alias[INDEX_PREFIX_POSITION_IN_ALIAS] !== this._indexPrefix ||
|
|
256
|
-
collectionName === HIDDEN_COLLECTION) {
|
|
257
|
-
continue;
|
|
258
|
-
}
|
|
259
|
-
const indexStats = (indexes[indexName] ?? (indexes[indexName] = {
|
|
260
|
-
collections: [],
|
|
261
|
-
name: indexName,
|
|
262
|
-
size: 0,
|
|
263
|
-
}));
|
|
264
|
-
// Both are there: the request asks for the `docs` and `store` metrics.
|
|
265
|
-
const sizeInBytes = indiceInfo.total?.store?.size_in_bytes ?? 0;
|
|
266
|
-
indexStats.collections.push({
|
|
267
|
-
documentCount: indiceInfo.total?.docs?.count ?? 0,
|
|
268
|
-
name: collectionName,
|
|
269
|
-
size: sizeInBytes,
|
|
270
|
-
});
|
|
271
|
-
indexStats.size += sizeInBytes;
|
|
272
|
-
size += sizeInBytes;
|
|
273
|
-
}
|
|
274
|
-
return {
|
|
275
|
-
indexes: Object.values(indexes),
|
|
276
|
-
size,
|
|
277
|
-
};
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* Scrolls results from previous elasticsearch query.
|
|
281
|
-
* Automatically clears the scroll context after the last result page has
|
|
282
|
-
* been fetched.
|
|
283
|
-
*
|
|
284
|
-
* @param {String} scrollId - Scroll identifier
|
|
285
|
-
* @param {Object} options - scrollTTL (default scrollTTL)
|
|
286
|
-
*
|
|
287
|
-
* @returns {Promise.<{ scrollId, hits, aggregations, total }>}
|
|
288
|
-
*/
|
|
289
|
-
async scroll(scrollId, { scrollTTL } = {}) {
|
|
290
|
-
const _scrollTTL = scrollTTL || this._config.defaults.scrollTTL;
|
|
291
|
-
const esRequest = {
|
|
292
|
-
scroll: _scrollTTL,
|
|
293
|
-
scroll_id: scrollId,
|
|
294
|
-
};
|
|
295
|
-
const cacheKey = SCROLL_CACHE_PREFIX + global.kuzzle.hash(esRequest.scroll_id);
|
|
296
|
-
this.logger.debug("Scroll: %o", esRequest);
|
|
297
|
-
if (_scrollTTL) {
|
|
298
|
-
const scrollDuration = (0, ms_1.default)(_scrollTTL) ?? 0;
|
|
299
|
-
if (scrollDuration > this.maxScrollDuration) {
|
|
300
|
-
throw kerror.get("services", "storage", "scroll_duration_too_great", _scrollTTL);
|
|
301
|
-
}
|
|
302
|
-
}
|
|
303
|
-
const stringifiedScrollInfo = await global.kuzzle.ask("core:cache:internal:get", cacheKey);
|
|
304
|
-
if (!stringifiedScrollInfo) {
|
|
305
|
-
throw kerror.get("services", "storage", "unknown_scroll_id");
|
|
306
|
-
}
|
|
307
|
-
const scrollInfo = JSON.parse(stringifiedScrollInfo);
|
|
308
|
-
try {
|
|
309
|
-
const body = await this._client.scroll(esRequest);
|
|
310
|
-
const totalHitsValue = this._getHitsTotalValue(body.hits);
|
|
311
|
-
scrollInfo.fetched += body.hits.hits.length;
|
|
312
|
-
if (scrollInfo.fetched >= totalHitsValue) {
|
|
313
|
-
this.logger.debug("Last scroll page fetched: deleting scroll %s", body._scroll_id);
|
|
314
|
-
await global.kuzzle.ask("core:cache:internal:del", cacheKey);
|
|
315
|
-
await this.clearScroll(body._scroll_id);
|
|
316
|
-
}
|
|
317
|
-
else {
|
|
318
|
-
await global.kuzzle.ask("core:cache:internal:store", cacheKey, JSON.stringify(scrollInfo), {
|
|
319
|
-
ttl: (0, ms_1.default)(_scrollTTL) || this.scrollTTL,
|
|
320
|
-
});
|
|
321
|
-
}
|
|
322
|
-
const remaining = totalHitsValue - scrollInfo.fetched;
|
|
323
|
-
return await this._formatSearchResult(body, remaining, scrollInfo);
|
|
324
|
-
}
|
|
325
|
-
catch (error) {
|
|
326
|
-
throw this._esWrapper.formatESError(error);
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
/**
|
|
330
|
-
* Searches documents from elasticsearch with a query
|
|
331
|
-
*
|
|
332
|
-
* @param {String} index - Index name
|
|
333
|
-
* @param {String} collection - Collection name
|
|
334
|
-
* @param {Object} searchBody - Search request body (query, sort, etc.)
|
|
335
|
-
* @param {Object} options - from (undefined), size (undefined), scroll (undefined)
|
|
336
|
-
*
|
|
337
|
-
* @returns {Promise.<{ scrollId, hits, aggregations, suggest, total }>}
|
|
338
|
-
*/
|
|
339
|
-
async search({ index, collection, searchBody, targets, } = {}, { from, size, scroll, } = {}) {
|
|
340
|
-
let esIndexes;
|
|
341
|
-
if (targets && targets.length > 0) {
|
|
342
|
-
esIndexes = this._targetsToIndexes(targets);
|
|
343
|
-
}
|
|
344
|
-
else {
|
|
345
|
-
if (index === undefined) {
|
|
346
|
-
throw kerror.get("services", "storage", "missing_argument", "index");
|
|
347
|
-
}
|
|
348
|
-
esIndexes = this._getAlias(index, collection);
|
|
349
|
-
}
|
|
350
|
-
const esRequest = {
|
|
351
|
-
...this._sanitizeSearchBody(searchBody),
|
|
352
|
-
from,
|
|
353
|
-
index: esIndexes,
|
|
354
|
-
scroll,
|
|
355
|
-
size,
|
|
356
|
-
track_total_hits: true,
|
|
357
|
-
};
|
|
358
|
-
if (scroll) {
|
|
359
|
-
const scrollDuration = (0, ms_1.default)(scroll) ?? 0;
|
|
360
|
-
if (scrollDuration > this.maxScrollDuration) {
|
|
361
|
-
throw kerror.get("services", "storage", "scroll_duration_too_great", scroll);
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
this.logger.debug("Search: %j", esRequest);
|
|
365
|
-
try {
|
|
366
|
-
const body = await this._client.search(esRequest);
|
|
367
|
-
const totalHitsValue = this._getHitsTotalValue(body.hits);
|
|
368
|
-
let remaining;
|
|
369
|
-
if (body._scroll_id) {
|
|
370
|
-
const scrollTTL = this._config.defaults.scrollTTL;
|
|
371
|
-
const ttl = (scroll && (0, ms_1.default)(scroll)) || (0, ms_1.default)(scrollTTL);
|
|
372
|
-
await global.kuzzle.ask("core:cache:internal:store", SCROLL_CACHE_PREFIX + global.kuzzle.hash(body._scroll_id), JSON.stringify({
|
|
373
|
-
collection,
|
|
374
|
-
fetched: body.hits.hits.length,
|
|
375
|
-
index,
|
|
376
|
-
targets,
|
|
377
|
-
}), { ttl });
|
|
378
|
-
remaining = totalHitsValue - body.hits.hits.length;
|
|
379
|
-
}
|
|
380
|
-
return await this._formatSearchResult(body, remaining, {
|
|
381
|
-
collection,
|
|
382
|
-
index,
|
|
383
|
-
targets,
|
|
384
|
-
});
|
|
385
|
-
}
|
|
386
|
-
catch (error) {
|
|
387
|
-
throw this._esWrapper.formatESError(error);
|
|
388
|
-
}
|
|
389
|
-
}
|
|
390
|
-
/**
|
|
391
|
-
* The comma-separated alias list a multi-target search is run against.
|
|
392
|
-
*
|
|
393
|
-
* @param targets - targets already through `assertTargetsAreValid`
|
|
394
|
-
*/
|
|
395
|
-
_targetsToIndexes(targets) {
|
|
396
|
-
const indexes = new Set();
|
|
397
|
-
for (const target of targets) {
|
|
398
|
-
for (const targetCollection of target.collections) {
|
|
399
|
-
indexes.add(this._getAlias(target.index, targetCollection));
|
|
400
|
-
}
|
|
401
|
-
}
|
|
402
|
-
return Array.from(indexes).join(",");
|
|
403
|
-
}
|
|
404
|
-
/**
|
|
405
|
-
* Generate a map that associate an alias to a pair of index and collection
|
|
406
|
-
*
|
|
407
|
-
* @param {*} targets
|
|
408
|
-
* @returns
|
|
409
|
-
*/
|
|
410
|
-
_mapTargetsToAlias(targets) {
|
|
411
|
-
const aliasToTargets = {};
|
|
412
|
-
for (const target of targets) {
|
|
413
|
-
for (const targetCollection of target.collections) {
|
|
414
|
-
const alias = this._getAlias(target.index, targetCollection);
|
|
415
|
-
if (!aliasToTargets[alias]) {
|
|
416
|
-
aliasToTargets[alias] = {
|
|
417
|
-
collection: targetCollection,
|
|
418
|
-
index: target.index,
|
|
419
|
-
};
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
return aliasToTargets;
|
|
424
|
-
}
|
|
425
|
-
async _formatSearchResult(body, remaining, searchInfo = {}) {
|
|
426
|
-
let aliasToTargets = {};
|
|
427
|
-
const aliasCache = new Map();
|
|
428
|
-
if (searchInfo.targets) {
|
|
429
|
-
/**
|
|
430
|
-
* We need to map the alias to the target index and collection,
|
|
431
|
-
* so we can later retrieve informations about an index & collection
|
|
432
|
-
* based on its alias.
|
|
433
|
-
*/
|
|
434
|
-
aliasToTargets = this._mapTargetsToAlias(searchInfo.targets);
|
|
435
|
-
}
|
|
436
|
-
const formatHit = async (hit) => {
|
|
437
|
-
let index = searchInfo.index;
|
|
438
|
-
let collection = searchInfo.collection;
|
|
439
|
-
/**
|
|
440
|
-
* If the search has been done on multiple targets, we need to
|
|
441
|
-
* retrieve the appropriate index and collection based on the alias
|
|
442
|
-
*/
|
|
443
|
-
if (hit._index && searchInfo.targets) {
|
|
444
|
-
// Caching to reduce call to ES
|
|
445
|
-
let aliases = aliasCache.get(hit._index);
|
|
446
|
-
if (!aliases) {
|
|
447
|
-
// Retrieve all the alias associated to one index
|
|
448
|
-
aliases = await this._getAliasFromIndice(hit._index);
|
|
449
|
-
aliasCache.set(hit._index, aliases);
|
|
450
|
-
}
|
|
451
|
-
/**
|
|
452
|
-
* Since multiple alias can point to the same index in ES, we need to
|
|
453
|
-
* find the first alias that exists in the map of aliases associated
|
|
454
|
-
* to the targets.
|
|
455
|
-
*/
|
|
456
|
-
// Retrieve index and collection information based on the matching alias
|
|
457
|
-
for (const _alias of aliases) {
|
|
458
|
-
const target = aliasToTargets[_alias];
|
|
459
|
-
if (target) {
|
|
460
|
-
index = target.index;
|
|
461
|
-
collection = target.collection;
|
|
462
|
-
break;
|
|
463
|
-
}
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
return {
|
|
467
|
-
_id: hit._id,
|
|
468
|
-
_score: hit._score,
|
|
469
|
-
_source: hit._source,
|
|
470
|
-
collection,
|
|
471
|
-
highlight: hit.highlight,
|
|
472
|
-
index,
|
|
473
|
-
};
|
|
474
|
-
};
|
|
475
|
-
async function formatInnerHits(innerHits) {
|
|
476
|
-
if (!innerHits) {
|
|
477
|
-
return undefined;
|
|
478
|
-
}
|
|
479
|
-
const formatted = await Promise.all(Object.entries(innerHits).map(async ([name, innerHit]) => [
|
|
480
|
-
name,
|
|
481
|
-
await bluebird_1.default.map(innerHit.hits.hits, formatHit),
|
|
482
|
-
]));
|
|
483
|
-
return Object.fromEntries(formatted);
|
|
484
|
-
}
|
|
485
|
-
const hits = await bluebird_1.default.map(body.hits.hits, async (hit) => ({
|
|
486
|
-
inner_hits: await formatInnerHits(hit.inner_hits),
|
|
487
|
-
...(await formatHit(hit)),
|
|
488
|
-
}));
|
|
489
|
-
return {
|
|
490
|
-
aggregations: body.aggregations,
|
|
491
|
-
hits,
|
|
492
|
-
remaining,
|
|
493
|
-
scrollId: body._scroll_id,
|
|
494
|
-
suggest: body.suggest,
|
|
495
|
-
total: this._getHitsTotalValue(body.hits),
|
|
496
|
-
};
|
|
497
|
-
}
|
|
498
|
-
/**
|
|
499
|
-
* Gets the document with given ID
|
|
500
|
-
*
|
|
501
|
-
* @param {String} index - Index name
|
|
502
|
-
* @param {String} collection - Collection name
|
|
503
|
-
* @param {String} id - Document ID
|
|
504
|
-
*
|
|
505
|
-
* @returns {Promise.<{ _id, _version, _source }>}
|
|
506
|
-
*/
|
|
507
|
-
async get(index, collection, id) {
|
|
508
|
-
const esRequest = {
|
|
509
|
-
id,
|
|
510
|
-
index: this._getAlias(index, collection),
|
|
511
|
-
};
|
|
512
|
-
// Just in case the user make a GET on url /mainindex/test/_search
|
|
513
|
-
// Without this test we return something weird: a result.hits.hits with all
|
|
514
|
-
// document without filter because the body is empty in HTTP by default
|
|
515
|
-
if (esRequest.id === "_search") {
|
|
516
|
-
return kerror.reject("services", "storage", "search_as_an_id");
|
|
517
|
-
}
|
|
518
|
-
this.logger.debug("Get document: %o", esRequest);
|
|
519
|
-
try {
|
|
520
|
-
const body = await this._client.get(esRequest);
|
|
521
|
-
return {
|
|
522
|
-
_id: body._id,
|
|
523
|
-
_source: body._source,
|
|
524
|
-
_version: body._version,
|
|
525
|
-
};
|
|
526
|
-
}
|
|
527
|
-
catch (error) {
|
|
528
|
-
throw this._esWrapper.formatESError(error);
|
|
529
|
-
}
|
|
530
|
-
}
|
|
531
|
-
/**
|
|
532
|
-
* Returns the list of documents matching the ids given in the body param
|
|
533
|
-
* NB: Due to internal Kuzzle mechanism, can only be called on a single
|
|
534
|
-
* index/collection, using the body { ids: [.. } syntax.
|
|
535
|
-
*
|
|
536
|
-
* @param {String} index - Index name
|
|
537
|
-
* @param {String} collection - Collection name
|
|
538
|
-
* @param {Array.<String>} ids - Document IDs
|
|
539
|
-
*
|
|
540
|
-
* @returns {Promise.<{ items: Array<{ _id, _source, _version }>, errors }>}
|
|
541
|
-
*/
|
|
542
|
-
async mGet(index, collection, ids) {
|
|
543
|
-
if (ids.length === 0) {
|
|
544
|
-
return { errors: [], items: [] };
|
|
545
|
-
}
|
|
546
|
-
const esRequest = {
|
|
547
|
-
docs: ids.map((_id) => ({
|
|
548
|
-
_id,
|
|
549
|
-
_index: this._getAlias(index, collection),
|
|
550
|
-
})),
|
|
551
|
-
};
|
|
552
|
-
this.logger.debug("Multi-get documents: %o", esRequest);
|
|
553
|
-
let body;
|
|
554
|
-
try {
|
|
555
|
-
body = await this._client.mget(esRequest); // NOSONAR
|
|
556
|
-
}
|
|
557
|
-
catch (e) {
|
|
558
|
-
throw this._esWrapper.formatESError(e);
|
|
559
|
-
}
|
|
560
|
-
const errors = [];
|
|
561
|
-
const items = [];
|
|
562
|
-
for (const doc of body.docs) {
|
|
563
|
-
if (!("error" in doc) && doc.found) {
|
|
564
|
-
items.push({
|
|
565
|
-
_id: doc._id,
|
|
566
|
-
_source: doc._source,
|
|
567
|
-
_version: doc._version,
|
|
568
|
-
});
|
|
569
|
-
}
|
|
570
|
-
else {
|
|
571
|
-
errors.push(doc._id);
|
|
572
|
-
}
|
|
573
|
-
}
|
|
574
|
-
return { errors, items };
|
|
575
|
-
}
|
|
576
|
-
/**
|
|
577
|
-
* Counts how many documents match the filter given in body
|
|
578
|
-
*
|
|
579
|
-
* @param {String} index - Index name
|
|
580
|
-
* @param {String} collection - Collection name
|
|
581
|
-
* @param {Object} searchBody - Search request body (query, sort, etc.)
|
|
582
|
-
*
|
|
583
|
-
* @returns {Promise.<Number>} count
|
|
584
|
-
*/
|
|
585
|
-
async count(index, collection, searchBody = {}) {
|
|
586
|
-
const esRequest = {
|
|
587
|
-
...this._sanitizeSearchBody(searchBody),
|
|
588
|
-
index: this._getAlias(index, collection),
|
|
589
|
-
};
|
|
590
|
-
this.logger.debug("Count: %o", esRequest);
|
|
591
|
-
try {
|
|
592
|
-
const body = await this._client.count(esRequest);
|
|
593
|
-
return body.count;
|
|
594
|
-
}
|
|
595
|
-
catch (error) {
|
|
596
|
-
throw this._esWrapper.formatESError(error);
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
/**
|
|
600
|
-
* Sends the new document to elasticsearch
|
|
601
|
-
* Cleans data to match elasticsearch specifications
|
|
602
|
-
*
|
|
603
|
-
* @param {String} index - Index name
|
|
604
|
-
* @param {String} collection - Collection name
|
|
605
|
-
* @param {Object} content - Document content
|
|
606
|
-
* @param {Object} options - id (undefined), refresh (undefined), userId (null)
|
|
607
|
-
*
|
|
608
|
-
* @returns {Promise.<Object>} { _id, _version, _source }
|
|
609
|
-
*/
|
|
610
|
-
async create(index, collection, content, { id, refresh, userId = null, injectKuzzleMeta = true, } = {}) {
|
|
611
|
-
(0, requestAssertions_1.assertIsObject)(content);
|
|
612
|
-
// `document` is optional on an IndexRequest, so the metadata is written
|
|
613
|
-
// through the local the request holds by reference rather than read back
|
|
614
|
-
// off the request.
|
|
615
|
-
const document = content;
|
|
616
|
-
const esRequest = {
|
|
617
|
-
document,
|
|
618
|
-
id,
|
|
619
|
-
index: this._getAlias(index, collection),
|
|
620
|
-
op_type: id ? "create" : "index",
|
|
621
|
-
refresh,
|
|
622
|
-
};
|
|
623
|
-
assertNoRouting(esRequest);
|
|
624
|
-
assertWellFormedRefresh(esRequest);
|
|
625
|
-
// Add metadata
|
|
626
|
-
if (injectKuzzleMeta) {
|
|
627
|
-
document._kuzzle_info = {
|
|
628
|
-
author: getKuid(userId),
|
|
629
|
-
createdAt: Date.now(),
|
|
630
|
-
updatedAt: null,
|
|
631
|
-
updater: null,
|
|
632
|
-
};
|
|
633
|
-
}
|
|
634
|
-
this.logger.debug("Create document: %o", esRequest);
|
|
635
|
-
try {
|
|
636
|
-
const body = await this._client.index(esRequest);
|
|
637
|
-
return {
|
|
638
|
-
_id: body._id,
|
|
639
|
-
_source: document,
|
|
640
|
-
_version: body._version,
|
|
641
|
-
};
|
|
642
|
-
}
|
|
643
|
-
catch (error) {
|
|
644
|
-
throw this._esWrapper.formatESError(error);
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
/**
|
|
648
|
-
* Creates a new document to Elasticsearch, or replace it if it already exist
|
|
649
|
-
*
|
|
650
|
-
* @param {String} index - Index name
|
|
651
|
-
* @param {String} collection - Collection name
|
|
652
|
-
* @param {String} id - Document id
|
|
653
|
-
* @param {Object} content - Document content
|
|
654
|
-
* @param {Object} options - refresh (undefined), userId (null), injectKuzzleMeta (true)
|
|
655
|
-
*
|
|
656
|
-
* @returns {Promise.<Object>} { _id, _version, _source, created }
|
|
657
|
-
*/
|
|
658
|
-
async createOrReplace(index, collection, id, content, { refresh, userId = null, injectKuzzleMeta = true, } = {}) {
|
|
659
|
-
const document = content;
|
|
660
|
-
const esRequest = {
|
|
661
|
-
document,
|
|
662
|
-
id,
|
|
663
|
-
index: this._getAlias(index, collection),
|
|
664
|
-
refresh,
|
|
665
|
-
};
|
|
666
|
-
assertNoRouting(esRequest);
|
|
667
|
-
assertWellFormedRefresh(esRequest);
|
|
668
|
-
// Add metadata
|
|
669
|
-
if (injectKuzzleMeta) {
|
|
670
|
-
document._kuzzle_info = {
|
|
671
|
-
author: getKuid(userId),
|
|
672
|
-
createdAt: Date.now(),
|
|
673
|
-
updatedAt: Date.now(),
|
|
674
|
-
updater: getKuid(userId),
|
|
675
|
-
};
|
|
676
|
-
}
|
|
677
|
-
this.logger.debug("Create or replace document: %o", esRequest);
|
|
678
|
-
try {
|
|
679
|
-
const body = await this._client.index(esRequest);
|
|
680
|
-
return {
|
|
681
|
-
_id: body._id,
|
|
682
|
-
_source: document,
|
|
683
|
-
_version: body._version,
|
|
684
|
-
created: body.result === "created", // Needed by the notifier
|
|
685
|
-
};
|
|
686
|
-
}
|
|
687
|
-
catch (error) {
|
|
688
|
-
throw this._esWrapper.formatESError(error);
|
|
689
|
-
}
|
|
690
|
-
}
|
|
691
|
-
/**
|
|
692
|
-
* Sends the partial document to elasticsearch with the id to update
|
|
693
|
-
*
|
|
694
|
-
* @param {String} index - Index name
|
|
695
|
-
* @param {String} collection - Collection name
|
|
696
|
-
* @param {String} id - Document id
|
|
697
|
-
* @param {Object} content - Updated content
|
|
698
|
-
* @param {Object} options - refresh (undefined), userId (null), retryOnConflict (0)
|
|
699
|
-
*
|
|
700
|
-
* @returns {Promise.<{ _id, _version }>}
|
|
701
|
-
*/
|
|
702
|
-
async update(index, collection, id, content, { refresh, userId = null, retryOnConflict, injectKuzzleMeta = true, } = {}) {
|
|
703
|
-
const doc = content;
|
|
704
|
-
const esRequest = {
|
|
705
|
-
_source: true,
|
|
706
|
-
doc,
|
|
707
|
-
id,
|
|
708
|
-
index: this._getAlias(index, collection),
|
|
709
|
-
refresh,
|
|
710
|
-
retry_on_conflict: retryOnConflict || this._config.defaults.onUpdateConflictRetries,
|
|
711
|
-
};
|
|
712
|
-
assertNoRouting(esRequest);
|
|
713
|
-
assertWellFormedRefresh(esRequest);
|
|
714
|
-
if (injectKuzzleMeta) {
|
|
715
|
-
// Add metadata
|
|
716
|
-
doc._kuzzle_info = {
|
|
717
|
-
...doc._kuzzle_info,
|
|
718
|
-
updatedAt: Date.now(),
|
|
719
|
-
updater: getKuid(userId),
|
|
720
|
-
};
|
|
721
|
-
}
|
|
722
|
-
this.logger.debug("Update document: %o", esRequest);
|
|
723
|
-
try {
|
|
724
|
-
const body = await this._client.update(esRequest);
|
|
725
|
-
return {
|
|
726
|
-
_id: body._id,
|
|
727
|
-
_source: body.get?._source,
|
|
728
|
-
_version: body._version,
|
|
729
|
-
};
|
|
730
|
-
}
|
|
731
|
-
catch (error) {
|
|
732
|
-
throw this._esWrapper.formatESError(error);
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
/**
|
|
736
|
-
* Sends the partial document to elasticsearch with the id to update
|
|
737
|
-
* Creates the document if it doesn't already exist
|
|
738
|
-
*
|
|
739
|
-
* @param {String} index - Index name
|
|
740
|
-
* @param {String} collection - Collection name
|
|
741
|
-
* @param {String} id - Document id
|
|
742
|
-
* @param {Object} content - Updated content
|
|
743
|
-
* @param {Object} options - defaultValues ({}), refresh (undefined), userId (null), retryOnConflict (0)
|
|
744
|
-
*
|
|
745
|
-
* @returns {Promise.<{ _id, _version }>}
|
|
746
|
-
*/
|
|
747
|
-
async upsert(index, collection, id, content, { defaultValues = {}, refresh, userId = null, retryOnConflict, injectKuzzleMeta = true, } = {}) {
|
|
748
|
-
const doc = content;
|
|
749
|
-
const upsert = { ...defaultValues, ...content };
|
|
750
|
-
const esRequest = {
|
|
751
|
-
_source: true,
|
|
752
|
-
doc,
|
|
753
|
-
id,
|
|
754
|
-
index: this._getAlias(index, collection),
|
|
755
|
-
refresh,
|
|
756
|
-
retry_on_conflict: retryOnConflict || this._config.defaults.onUpdateConflictRetries,
|
|
757
|
-
upsert,
|
|
758
|
-
};
|
|
759
|
-
assertNoRouting(esRequest);
|
|
760
|
-
assertWellFormedRefresh(esRequest);
|
|
761
|
-
// Add metadata
|
|
762
|
-
const user = getKuid(userId);
|
|
763
|
-
const now = Date.now();
|
|
764
|
-
if (injectKuzzleMeta) {
|
|
765
|
-
doc._kuzzle_info = {
|
|
766
|
-
...doc._kuzzle_info,
|
|
767
|
-
updatedAt: now,
|
|
768
|
-
updater: user,
|
|
769
|
-
};
|
|
770
|
-
upsert._kuzzle_info = {
|
|
771
|
-
...upsert._kuzzle_info,
|
|
772
|
-
author: user,
|
|
773
|
-
createdAt: now,
|
|
774
|
-
};
|
|
775
|
-
}
|
|
776
|
-
this.logger.debug("Upsert document: %o", esRequest);
|
|
777
|
-
try {
|
|
778
|
-
const body = await this._client.update(esRequest);
|
|
779
|
-
return {
|
|
780
|
-
_id: body._id,
|
|
781
|
-
_source: body.get?._source,
|
|
782
|
-
_version: body._version,
|
|
783
|
-
created: body.result === "created",
|
|
784
|
-
};
|
|
785
|
-
}
|
|
786
|
-
catch (error) {
|
|
787
|
-
throw this._esWrapper.formatESError(error);
|
|
788
|
-
}
|
|
789
|
-
}
|
|
790
|
-
/**
|
|
791
|
-
* Replaces a document to Elasticsearch
|
|
792
|
-
*
|
|
793
|
-
* @param {String} index - Index name
|
|
794
|
-
* @param {String} collection - Collection name
|
|
795
|
-
* @param {String} id - Document id
|
|
796
|
-
* @param {Object} content - Document content
|
|
797
|
-
* @param {Object} options - refresh (undefined), userId (null)
|
|
798
|
-
*
|
|
799
|
-
* @returns {Promise.<{ _id, _version, _source }>}
|
|
800
|
-
*/
|
|
801
|
-
async replace(index, collection, id, content, { refresh, userId = null, injectKuzzleMeta = true, } = {}) {
|
|
802
|
-
const alias = this._getAlias(index, collection);
|
|
803
|
-
const document = content;
|
|
804
|
-
const esRequest = {
|
|
805
|
-
document,
|
|
806
|
-
id,
|
|
807
|
-
index: alias,
|
|
808
|
-
refresh,
|
|
809
|
-
};
|
|
810
|
-
assertNoRouting(esRequest);
|
|
811
|
-
assertWellFormedRefresh(esRequest);
|
|
812
|
-
if (injectKuzzleMeta) {
|
|
813
|
-
// Add metadata
|
|
814
|
-
document._kuzzle_info = {
|
|
815
|
-
author: getKuid(userId),
|
|
816
|
-
createdAt: Date.now(),
|
|
817
|
-
updatedAt: Date.now(),
|
|
818
|
-
updater: getKuid(userId),
|
|
819
|
-
};
|
|
820
|
-
}
|
|
821
|
-
try {
|
|
822
|
-
const exists = await this._client.exists({ id, index: alias });
|
|
823
|
-
if (!exists) {
|
|
824
|
-
throw kerror.get("services", "storage", "not_found", id, index, collection);
|
|
825
|
-
}
|
|
826
|
-
this.logger.debug("Replace document: %o", esRequest);
|
|
827
|
-
const body = await this._client.index(esRequest);
|
|
828
|
-
return {
|
|
829
|
-
_id: id,
|
|
830
|
-
_source: esRequest.document,
|
|
831
|
-
_version: body._version,
|
|
832
|
-
};
|
|
833
|
-
}
|
|
834
|
-
catch (error) {
|
|
835
|
-
throw this._esWrapper.formatESError(error);
|
|
836
|
-
}
|
|
837
|
-
}
|
|
838
|
-
/**
|
|
839
|
-
* Sends to elasticsearch the document id to delete
|
|
840
|
-
*
|
|
841
|
-
* @param {String} index - Index name
|
|
842
|
-
* @param {String} collection - Collection name
|
|
843
|
-
* @param {String} id - Document id
|
|
844
|
-
* @param {Object} options - refresh (undefined)
|
|
845
|
-
*
|
|
846
|
-
* @returns {Promise}
|
|
847
|
-
*/
|
|
848
|
-
async delete(index, collection, id, { refresh, } = {}) {
|
|
849
|
-
const esRequest = {
|
|
850
|
-
id,
|
|
851
|
-
index: this._getAlias(index, collection),
|
|
852
|
-
refresh,
|
|
853
|
-
};
|
|
854
|
-
assertWellFormedRefresh(esRequest);
|
|
855
|
-
this.logger.debug("Delete document: %o", esRequest);
|
|
856
|
-
try {
|
|
857
|
-
await this._client.delete(esRequest);
|
|
858
|
-
}
|
|
859
|
-
catch (error) {
|
|
860
|
-
throw this._esWrapper.formatESError(error);
|
|
861
|
-
}
|
|
862
|
-
return null;
|
|
863
|
-
}
|
|
864
|
-
/**
|
|
865
|
-
* Deletes all documents matching the provided filters.
|
|
866
|
-
* If fetch=false, the max documents write limit is not applied.
|
|
867
|
-
*
|
|
868
|
-
* Options:
|
|
869
|
-
* - size: size of the batch to retrieve documents (no-op if fetch=false)
|
|
870
|
-
* - refresh: refresh option for ES
|
|
871
|
-
* - fetch: if true, will fetch the documents before delete them
|
|
872
|
-
*
|
|
873
|
-
* @param {String} index - Index name
|
|
874
|
-
* @param {String} collection - Collection name
|
|
875
|
-
* @param {Object} query - Query to match documents
|
|
876
|
-
* @param {Object} options - size (undefined), refresh (undefined), fetch (true)
|
|
877
|
-
*
|
|
878
|
-
* @returns {Promise.<{ documents, total, deleted, failures: Array<{ id, reason }> }>}
|
|
879
|
-
*/
|
|
880
|
-
async deleteByQuery(index, collection, query, { refresh, size = 1000, fetch = true, } = {}) {
|
|
881
|
-
const esRequest = {
|
|
882
|
-
...this._sanitizeSearchBody({ query }),
|
|
883
|
-
index: this._getAlias(index, collection),
|
|
884
|
-
scroll: "5s",
|
|
885
|
-
};
|
|
886
|
-
if (!(0, safeObject_1.isPlainObject)(query)) {
|
|
887
|
-
throw kerror.get("services", "storage", "missing_argument", "body.query");
|
|
888
|
-
}
|
|
889
|
-
try {
|
|
890
|
-
let documents = [];
|
|
891
|
-
if (fetch) {
|
|
892
|
-
documents = await this._getAllDocumentsFromQuery({
|
|
893
|
-
...esRequest,
|
|
894
|
-
size,
|
|
895
|
-
});
|
|
896
|
-
}
|
|
897
|
-
this.logger.debug("Delete by query: %o", esRequest);
|
|
898
|
-
const request = {
|
|
899
|
-
...esRequest,
|
|
900
|
-
// Built in rather than assigned onto `esRequest` afterwards: that
|
|
901
|
-
// object is spread into the search above, and mutating it after the
|
|
902
|
-
// fact meant its declared shape and its real one disagreed.
|
|
903
|
-
refresh: refresh === "wait_for" ? true : refresh,
|
|
904
|
-
// -1 is Kuzzle's "no limit"; ES wants the property absent rather than
|
|
905
|
-
// set to undefined after the fact, which was a `number` field being
|
|
906
|
-
// assigned undefined.
|
|
907
|
-
max_docs: size === -1 ? undefined : size,
|
|
908
|
-
};
|
|
909
|
-
const body = await this._client.deleteByQuery(request);
|
|
910
|
-
return {
|
|
911
|
-
deleted: body.deleted,
|
|
912
|
-
documents,
|
|
913
|
-
failures: (body.failures ?? []).map(({ id, cause }) => ({
|
|
914
|
-
id,
|
|
915
|
-
reason: cause?.reason,
|
|
916
|
-
})),
|
|
917
|
-
total: body.total,
|
|
918
|
-
};
|
|
919
|
-
}
|
|
920
|
-
catch (error) {
|
|
921
|
-
throw this._esWrapper.formatESError(error);
|
|
922
|
-
}
|
|
923
|
-
}
|
|
924
|
-
/**
|
|
925
|
-
* Delete fields of a document and replace it
|
|
926
|
-
*
|
|
927
|
-
* @param {String} index - Index name
|
|
928
|
-
* @param {String} collection - Collection name
|
|
929
|
-
* @param {String} id - Document id
|
|
930
|
-
* @param {Array} fields - Document fields to be removed
|
|
931
|
-
* @param {Object} options - refresh (undefined), userId (null)
|
|
932
|
-
*
|
|
933
|
-
* @returns {Promise.<{ _id, _version, _source }>}
|
|
934
|
-
*/
|
|
935
|
-
async deleteFields(index, collection, id, fields, { refresh, userId = null, } = {}) {
|
|
936
|
-
const alias = this._getAlias(index, collection);
|
|
937
|
-
const esRequest = {
|
|
938
|
-
id,
|
|
939
|
-
index: alias,
|
|
940
|
-
};
|
|
941
|
-
try {
|
|
942
|
-
this.logger.debug("DeleteFields document: %o", esRequest);
|
|
943
|
-
const body = await this._client.get(esRequest);
|
|
944
|
-
const source = body._source;
|
|
945
|
-
if (source === undefined) {
|
|
946
|
-
throw kerror.get("services", "storage", "not_found", id, index, collection);
|
|
947
|
-
}
|
|
948
|
-
for (const field of fields) {
|
|
949
|
-
if (lodash_1.default.has(source, field)) {
|
|
950
|
-
lodash_1.default.set(source, field, undefined);
|
|
951
|
-
}
|
|
952
|
-
}
|
|
953
|
-
const updatedInfos = {
|
|
954
|
-
updatedAt: Date.now(),
|
|
955
|
-
updater: getKuid(userId),
|
|
956
|
-
};
|
|
957
|
-
if (typeof source._kuzzle_info === "object") {
|
|
958
|
-
source._kuzzle_info = {
|
|
959
|
-
...source._kuzzle_info,
|
|
960
|
-
...updatedInfos,
|
|
961
|
-
};
|
|
962
|
-
}
|
|
963
|
-
else {
|
|
964
|
-
source._kuzzle_info = updatedInfos;
|
|
965
|
-
}
|
|
966
|
-
const newEsRequest = {
|
|
967
|
-
document: source,
|
|
968
|
-
id,
|
|
969
|
-
index: alias,
|
|
970
|
-
refresh,
|
|
971
|
-
};
|
|
972
|
-
assertNoRouting(newEsRequest);
|
|
973
|
-
assertWellFormedRefresh(newEsRequest);
|
|
974
|
-
const updated = await this._client.index(newEsRequest);
|
|
975
|
-
return {
|
|
976
|
-
_id: id,
|
|
977
|
-
_source: source,
|
|
978
|
-
_version: updated._version,
|
|
979
|
-
};
|
|
980
|
-
}
|
|
981
|
-
catch (error) {
|
|
982
|
-
throw this._esWrapper.formatESError(error);
|
|
983
|
-
}
|
|
984
|
-
}
|
|
985
|
-
/**
|
|
986
|
-
* Updates all documents matching the provided filters
|
|
987
|
-
*
|
|
988
|
-
* @param {String} index - Index name
|
|
989
|
-
* @param {String} collection - Collection name
|
|
990
|
-
* @param {Object} query - Query to match documents
|
|
991
|
-
* @param {Object} changes - Changes wanted on documents
|
|
992
|
-
* @param {Object} options - refresh (undefined), size (undefined)
|
|
993
|
-
*
|
|
994
|
-
* @returns {Promise.<{ successes: [_id, _source, _status], errors: [ document, status, reason ] }>}
|
|
995
|
-
*/
|
|
996
|
-
async updateByQuery(index, collection, query, changes, { refresh, size = 1000, userId = null, } = {}) {
|
|
997
|
-
try {
|
|
998
|
-
const esRequest = {
|
|
999
|
-
...this._sanitizeSearchBody({ query }),
|
|
1000
|
-
index: this._getAlias(index, collection),
|
|
1001
|
-
scroll: "5s",
|
|
1002
|
-
size,
|
|
1003
|
-
};
|
|
1004
|
-
const documents = await this._getAllDocumentsFromQuery(esRequest);
|
|
1005
|
-
for (const document of documents) {
|
|
1006
|
-
document._source = undefined;
|
|
1007
|
-
document.body = changes;
|
|
1008
|
-
}
|
|
1009
|
-
this.logger.debug("Update by query: %o", esRequest);
|
|
1010
|
-
const { errors, items } = await this.mUpdate(index, collection, documents, { refresh, userId });
|
|
1011
|
-
return {
|
|
1012
|
-
errors,
|
|
1013
|
-
successes: items,
|
|
1014
|
-
};
|
|
1015
|
-
}
|
|
1016
|
-
catch (error) {
|
|
1017
|
-
throw this._esWrapper.formatESError(error);
|
|
1018
|
-
}
|
|
1019
|
-
}
|
|
1020
|
-
/**
|
|
1021
|
-
* Updates all documents matching the provided filters
|
|
1022
|
-
*
|
|
1023
|
-
* @param {String} index - Index name
|
|
1024
|
-
* @param {String} collection - Collection name
|
|
1025
|
-
* @param {Object} query - Query to match documents
|
|
1026
|
-
* @param {Object} changes - Changes wanted on documents
|
|
1027
|
-
* @param {Object} options - refresh (undefined)
|
|
1028
|
-
*
|
|
1029
|
-
* @returns {Promise.<{ successes: [_id, _source, _status], errors: [ document, status, reason ] }>}
|
|
1030
|
-
*/
|
|
1031
|
-
async bulkUpdateByQuery(index, collection, query, changes, { refresh = false, } = {}) {
|
|
1032
|
-
const esRequest = {
|
|
1033
|
-
index: this._getAlias(index, collection),
|
|
1034
|
-
query: this._sanitizeSearchBody({ query }).query,
|
|
1035
|
-
refresh,
|
|
1036
|
-
};
|
|
1037
|
-
const script = {
|
|
1038
|
-
params: {},
|
|
1039
|
-
source: "",
|
|
1040
|
-
};
|
|
1041
|
-
const flatChanges = (0, extractFields_1.default)(changes, { alsoExtractValues: true });
|
|
1042
|
-
for (const { key, value } of flatChanges) {
|
|
1043
|
-
script.source += `ctx._source.${key} = params['${key}'];`;
|
|
1044
|
-
script.params[key] = value;
|
|
1045
|
-
}
|
|
1046
|
-
if (script.source !== "") {
|
|
1047
|
-
esRequest.script = script;
|
|
1048
|
-
}
|
|
1049
|
-
this.logger.debug("Bulk Update by query: %o", esRequest);
|
|
1050
|
-
let response;
|
|
1051
|
-
try {
|
|
1052
|
-
response = await this._client.updateByQuery(esRequest);
|
|
1053
|
-
}
|
|
1054
|
-
catch (error) {
|
|
1055
|
-
throw this._esWrapper.formatESError(error);
|
|
1056
|
-
}
|
|
1057
|
-
const failures = response.failures ?? [];
|
|
1058
|
-
if (failures.length) {
|
|
1059
|
-
const errors = failures.map(({ id, cause }) => ({
|
|
1060
|
-
cause,
|
|
1061
|
-
id,
|
|
1062
|
-
}));
|
|
1063
|
-
throw kerror.get("services", "storage", "incomplete_update", response.updated, errors);
|
|
1064
|
-
}
|
|
1065
|
-
return {
|
|
1066
|
-
updated: response.updated,
|
|
1067
|
-
};
|
|
1068
|
-
}
|
|
1069
|
-
/**
|
|
1070
|
-
* Execute the callback with a batch of documents of specified size until all
|
|
1071
|
-
* documents matched by the query have been processed.
|
|
1072
|
-
*
|
|
1073
|
-
* @param {String} index - Index name
|
|
1074
|
-
* @param {String} collection - Collection name
|
|
1075
|
-
* @param {Object} query - Query to match documents
|
|
1076
|
-
* @param {Function} callback - callback that will be called with the "hits" array
|
|
1077
|
-
* @param {Object} options - size (10), scrollTTL ('5s')
|
|
1078
|
-
*
|
|
1079
|
-
* @returns {Promise.<any[]>} Array of results returned by the callback
|
|
1080
|
-
*/
|
|
1081
|
-
async mExecute(index, collection, query, callback, { size = 10, scrollTTl = "5s", } = {}) {
|
|
1082
|
-
const esRequest = {
|
|
1083
|
-
...this._sanitizeSearchBody({ query }),
|
|
1084
|
-
from: 0,
|
|
1085
|
-
index: this._getAlias(index, collection),
|
|
1086
|
-
scroll: scrollTTl,
|
|
1087
|
-
size,
|
|
1088
|
-
};
|
|
1089
|
-
if (!(0, safeObject_1.isPlainObject)(query)) {
|
|
1090
|
-
throw kerror.get("services", "storage", "missing_argument", "body.query");
|
|
1091
|
-
}
|
|
1092
|
-
const results = [];
|
|
1093
|
-
let processed = 0;
|
|
1094
|
-
let scrollId;
|
|
1095
|
-
try {
|
|
1096
|
-
let body = await this._client.search(esRequest);
|
|
1097
|
-
const totalHitsValue = this._getHitsTotalValue(body.hits);
|
|
1098
|
-
while (processed < totalHitsValue && body.hits.hits.length > 0) {
|
|
1099
|
-
scrollId = body._scroll_id;
|
|
1100
|
-
results.push(await callback(body.hits.hits));
|
|
1101
|
-
processed += body.hits.hits.length;
|
|
1102
|
-
body = await this._client.scroll({
|
|
1103
|
-
scroll: esRequest.scroll,
|
|
1104
|
-
scroll_id: scrollId,
|
|
1105
|
-
});
|
|
1106
|
-
}
|
|
1107
|
-
}
|
|
1108
|
-
finally {
|
|
1109
|
-
await this.clearScroll(scrollId);
|
|
1110
|
-
}
|
|
1111
|
-
return results;
|
|
1112
|
-
}
|
|
1113
|
-
/**
|
|
1114
|
-
* Creates a new index.
|
|
1115
|
-
*
|
|
1116
|
-
* This methods creates an hidden collection in the provided index to be
|
|
1117
|
-
* able to list it.
|
|
1118
|
-
* This methods resolves if the index name does not already exists either as
|
|
1119
|
-
* private or public index.
|
|
1120
|
-
*
|
|
1121
|
-
* @param {String} index - Index name
|
|
1122
|
-
*
|
|
1123
|
-
* @returns {Promise}
|
|
1124
|
-
*/
|
|
1125
|
-
async createIndex(index) {
|
|
1126
|
-
this._assertValidIndexAndCollection(index);
|
|
1127
|
-
let body;
|
|
1128
|
-
try {
|
|
1129
|
-
body = await this._catAliases();
|
|
1130
|
-
}
|
|
1131
|
-
catch (error) {
|
|
1132
|
-
throw this._esWrapper.formatESError(error);
|
|
1133
|
-
}
|
|
1134
|
-
const aliases = body.map(({ alias: name }) => name);
|
|
1135
|
-
for (const alias of aliases) {
|
|
1136
|
-
const indexName = this._extractIndex(alias);
|
|
1137
|
-
if (index === indexName) {
|
|
1138
|
-
const indexType = alias[INDEX_PREFIX_POSITION_IN_ALIAS] === PRIVATE_PREFIX
|
|
1139
|
-
? "private"
|
|
1140
|
-
: "public";
|
|
1141
|
-
throw kerror.get("services", "storage", "index_already_exists", indexType, index);
|
|
1142
|
-
}
|
|
1143
|
-
}
|
|
1144
|
-
await this._createHiddenCollection(index);
|
|
1145
|
-
return null;
|
|
1146
|
-
}
|
|
1147
|
-
/**
|
|
1148
|
-
* Creates an empty collection.
|
|
1149
|
-
* Mappings and settings will be applied if supplied.
|
|
1150
|
-
*
|
|
1151
|
-
* @param {String} index - Index name
|
|
1152
|
-
* @param {String} collection - Collection name
|
|
1153
|
-
* @param {Object} config - mappings ({}), settings ({})
|
|
1154
|
-
*
|
|
1155
|
-
* @returns {Promise}
|
|
1156
|
-
*/
|
|
1157
|
-
async createCollection(index, collection, { mappings = {}, settings = {}, } = {}) {
|
|
1158
|
-
this._assertValidIndexAndCollection(index, collection);
|
|
1159
|
-
if (collection === HIDDEN_COLLECTION) {
|
|
1160
|
-
throw kerror.get("services", "storage", "collection_reserved", HIDDEN_COLLECTION);
|
|
1161
|
-
}
|
|
1162
|
-
const esRequest = {
|
|
1163
|
-
aliases: {
|
|
1164
|
-
[this._getAlias(index, collection)]: {},
|
|
1165
|
-
},
|
|
1166
|
-
index: await this._getAvailableIndice(index, collection),
|
|
1167
|
-
mappings: {},
|
|
1168
|
-
settings,
|
|
1169
|
-
wait_for_active_shards: await this._getWaitForActiveShards(),
|
|
1170
|
-
};
|
|
1171
|
-
this._checkDynamicProperty(mappings);
|
|
1172
|
-
const exists = await this.hasCollection(index, collection);
|
|
1173
|
-
if (exists) {
|
|
1174
|
-
return this._updateConcurrentlyCreatedCollection(index, collection, mappings, settings);
|
|
1175
|
-
}
|
|
1176
|
-
this._checkMappings(mappings);
|
|
1177
|
-
// Copies, not in-place changes: the race branch below must hand the
|
|
1178
|
-
// caller's own mappings and settings to `updateCollection`
|
|
1179
|
-
esRequest.mappings = {
|
|
1180
|
-
_meta: mappings._meta || this._config.commonMapping._meta,
|
|
1181
|
-
dynamic: mappings.dynamic || this._config.commonMapping.dynamic,
|
|
1182
|
-
properties: lodash_1.default.merge({}, mappings.properties, this._config.commonMapping.properties),
|
|
1183
|
-
};
|
|
1184
|
-
esRequest.settings = {
|
|
1185
|
-
...settings,
|
|
1186
|
-
number_of_replicas: settings.number_of_replicas ||
|
|
1187
|
-
this._config.defaultSettings.number_of_replicas,
|
|
1188
|
-
number_of_shards: settings.number_of_shards ||
|
|
1189
|
-
this._config.defaultSettings.number_of_shards,
|
|
1190
|
-
};
|
|
1191
|
-
try {
|
|
1192
|
-
await this._client.indices.create(esRequest);
|
|
1193
|
-
}
|
|
1194
|
-
catch (error) {
|
|
1195
|
-
if (lodash_1.default.get(error, "meta.body.error.type") ===
|
|
1196
|
-
"resource_already_exists_exception") {
|
|
1197
|
-
// race condition: the indice has been created between the "exists"
|
|
1198
|
-
// check above and this "create" attempt, by a request that may not
|
|
1199
|
-
// have waited for its shards yet. This request's mappings and
|
|
1200
|
-
// settings must still be applied, as if it had seen it exist
|
|
1201
|
-
return this._updateConcurrentlyCreatedCollection(index, collection, mappings, settings);
|
|
1202
|
-
}
|
|
1203
|
-
throw this._esWrapper.formatESError(error);
|
|
1204
|
-
}
|
|
1205
|
-
// Only once the real collection exists: dropping the placeholder first
|
|
1206
|
-
// would leave the index with no indice at all if the creation failed.
|
|
1207
|
-
// Lock and ES errors alike reach the caller through `formatESError`
|
|
1208
|
-
try {
|
|
1209
|
-
await (0, distributedLock_1.withLock)(`hiddenCollection/create/${index}`, async () => {
|
|
1210
|
-
if (await this._hasHiddenCollection(index)) {
|
|
1211
|
-
await this.deleteCollection(index, HIDDEN_COLLECTION);
|
|
1212
|
-
}
|
|
1213
|
-
}, HIDDEN_COLLECTION_LOCK);
|
|
1214
|
-
}
|
|
1215
|
-
catch (error) {
|
|
1216
|
-
throw this._esWrapper.formatESError(error);
|
|
1217
|
-
}
|
|
1218
|
-
return null;
|
|
1219
|
-
}
|
|
1220
|
-
/**
|
|
1221
|
-
* Applies the mappings and settings of a `createCollection` call to a
|
|
1222
|
-
* collection that already exists because another request created it,
|
|
1223
|
-
* maybe so recently that its primary shards are still initializing.
|
|
1224
|
-
*/
|
|
1225
|
-
async _updateConcurrentlyCreatedCollection(index, collection, mappings, settings) {
|
|
1226
|
-
await this.waitForCollectionShards(index, collection);
|
|
1227
|
-
return this.updateCollection(index, collection, { mappings, settings });
|
|
1228
|
-
}
|
|
1229
|
-
/**
|
|
1230
|
-
* Waits until the primary shards of a collection are active, for at most
|
|
1231
|
-
* `timeout`, and rejects if they are not by then.
|
|
1232
|
-
*
|
|
1233
|
-
* A collection another node has just created is in the cluster state, so
|
|
1234
|
-
* it exists, before its primary shard is active: until then, Elasticsearch
|
|
1235
|
-
* answers 503 to any document request on it. The node that creates a
|
|
1236
|
-
* collection waits for its shards (`wait_for_active_shards`); a node that
|
|
1237
|
-
* finds it already there calls this instead. It answers at once when the
|
|
1238
|
-
* shards are already active.
|
|
1239
|
-
*
|
|
1240
|
-
* A `yellow` status alone does not wait: Elasticsearch reports a new index
|
|
1241
|
-
* whose primaries are still initializing as `yellow` (#3074). Asking for as
|
|
1242
|
-
* many active shard copies as the index has primaries does, and, unlike
|
|
1243
|
-
* `wait_for_no_initializing_shards`, does not also wait for replicas that
|
|
1244
|
-
* are recovering, which a collection with data may take longer to do.
|
|
1245
|
-
*/
|
|
1246
|
-
async waitForCollectionShards(index, collection, timeout = COLLECTION_SHARDS_TIMEOUT) {
|
|
1247
|
-
const alias = this._getAlias(index, collection);
|
|
1248
|
-
try {
|
|
1249
|
-
const body = await this._client.indices.getSettings({
|
|
1250
|
-
index: alias,
|
|
1251
|
-
name: "index.number_of_shards",
|
|
1252
|
-
});
|
|
1253
|
-
const primaries = Object.values(body)[0]?.settings?.index?.number_of_shards;
|
|
1254
|
-
await this._client.cluster.health({
|
|
1255
|
-
index: alias,
|
|
1256
|
-
timeout,
|
|
1257
|
-
wait_for_active_shards: Number(primaries ?? 1),
|
|
1258
|
-
wait_for_status: "yellow",
|
|
1259
|
-
});
|
|
1260
|
-
}
|
|
1261
|
-
catch (error) {
|
|
1262
|
-
throw this._esWrapper.formatESError(error);
|
|
1263
|
-
}
|
|
1264
|
-
}
|
|
1265
|
-
/**
|
|
1266
|
-
* Retrieves settings definition for index/type
|
|
1267
|
-
*
|
|
1268
|
-
* @param {String} index - Index name
|
|
1269
|
-
* @param {String} collection - Collection name
|
|
1270
|
-
*
|
|
1271
|
-
* @returns {Promise.<{ settings }>}
|
|
1272
|
-
*/
|
|
1273
|
-
async getSettings(index, collection) {
|
|
1274
|
-
const indice = await this._getIndice(index, collection);
|
|
1275
|
-
const esRequest = {
|
|
1276
|
-
index: indice,
|
|
1277
|
-
};
|
|
1278
|
-
this.logger.debug("Get settings: %o", esRequest);
|
|
1279
|
-
try {
|
|
1280
|
-
const body = await this._client.indices.getSettings(esRequest);
|
|
1281
|
-
return body[indice]?.settings?.index;
|
|
1282
|
-
}
|
|
1283
|
-
catch (error) {
|
|
1284
|
-
throw this._esWrapper.formatESError(error);
|
|
1285
|
-
}
|
|
1286
|
-
}
|
|
1287
|
-
/**
|
|
1288
|
-
* Retrieves mapping definition for index/type
|
|
1289
|
-
*
|
|
1290
|
-
* @param {String} index - Index name
|
|
1291
|
-
* @param {String} collection - Collection name
|
|
1292
|
-
* @param {Object} options - includeKuzzleMeta (false)
|
|
1293
|
-
*
|
|
1294
|
-
* @returns {Promise.<{ dynamic, _meta, properties }>}
|
|
1295
|
-
*/
|
|
1296
|
-
async getMapping(index, collection, { includeKuzzleMeta = false, } = {}) {
|
|
1297
|
-
const indice = await this._getIndice(index, collection);
|
|
1298
|
-
const esRequest = {
|
|
1299
|
-
index: indice,
|
|
1300
|
-
};
|
|
1301
|
-
this.logger.debug("Get mapping: %o", esRequest);
|
|
1302
|
-
try {
|
|
1303
|
-
const body = await this._client.indices.getMapping(esRequest);
|
|
1304
|
-
const mappings = body[indice]?.mappings ?? {};
|
|
1305
|
-
const properties = includeKuzzleMeta
|
|
1306
|
-
? mappings.properties
|
|
1307
|
-
: lodash_1.default.omit(mappings.properties, "_kuzzle_info");
|
|
1308
|
-
return {
|
|
1309
|
-
_meta: mappings._meta,
|
|
1310
|
-
dynamic: mappings.dynamic,
|
|
1311
|
-
properties,
|
|
1312
|
-
};
|
|
1313
|
-
}
|
|
1314
|
-
catch (error) {
|
|
1315
|
-
throw this._esWrapper.formatESError(error);
|
|
1316
|
-
}
|
|
1317
|
-
}
|
|
1318
|
-
/**
|
|
1319
|
-
* Updates a collection mappings and settings
|
|
1320
|
-
*
|
|
1321
|
-
* @param {String} index - Index name
|
|
1322
|
-
* @param {String} collection - Collection name
|
|
1323
|
-
* @param {Object} config - mappings ({}), settings ({})
|
|
1324
|
-
*
|
|
1325
|
-
* @returns {Promise}
|
|
1326
|
-
*/
|
|
1327
|
-
async updateCollection(index, collection, { mappings = {}, reindexCollection = false, settings = {}, } = {}) {
|
|
1328
|
-
const esRequest = {
|
|
1329
|
-
index: await this._getIndice(index, collection),
|
|
1330
|
-
};
|
|
1331
|
-
// If either the putMappings or the putSettings operation fail, we need to
|
|
1332
|
-
// rollback the whole operation. Since mappings can't be rollback, we try to
|
|
1333
|
-
// update the settings first, then the mappings and we rollback the settings
|
|
1334
|
-
// if putMappings fail.
|
|
1335
|
-
let indexSettings;
|
|
1336
|
-
try {
|
|
1337
|
-
indexSettings = await this._getSettings(esRequest);
|
|
1338
|
-
}
|
|
1339
|
-
catch (error) {
|
|
1340
|
-
throw this._esWrapper.formatESError(error);
|
|
1341
|
-
}
|
|
1342
|
-
if (!lodash_1.default.isEmpty(settings)) {
|
|
1343
|
-
await this.updateSettings(index, collection, settings);
|
|
1344
|
-
}
|
|
1345
|
-
try {
|
|
1346
|
-
if (!lodash_1.default.isEmpty(mappings)) {
|
|
1347
|
-
const previousMappings = await this.getMapping(index, collection, {
|
|
1348
|
-
includeKuzzleMeta: true,
|
|
1349
|
-
});
|
|
1350
|
-
await this.updateMapping(index, collection, mappings);
|
|
1351
|
-
if (reindexCollection ||
|
|
1352
|
-
this._dynamicChanges(previousMappings, mappings)) {
|
|
1353
|
-
await this.updateSearchIndex(index, collection);
|
|
1354
|
-
}
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
1357
|
-
catch (error) {
|
|
1358
|
-
const allowedSettings = this.getAllowedIndexSettings(indexSettings);
|
|
1359
|
-
// Rollback to previous settings
|
|
1360
|
-
if (!lodash_1.default.isEmpty(settings)) {
|
|
1361
|
-
await this.updateSettings(index, collection, allowedSettings);
|
|
1362
|
-
}
|
|
1363
|
-
throw error;
|
|
1364
|
-
}
|
|
1365
|
-
return null;
|
|
1366
|
-
}
|
|
1367
|
-
/**
|
|
1368
|
-
* Given index settings we return a new version of index settings
|
|
1369
|
-
* only with allowed settings that can be set (during update or create index).
|
|
1370
|
-
* @param indexSettings the index settings
|
|
1371
|
-
* @returns {{index: *}} a new index settings with only allowed settings.
|
|
1372
|
-
*/
|
|
1373
|
-
getAllowedIndexSettings(indexSettings) {
|
|
1374
|
-
return {
|
|
1375
|
-
index: lodash_1.default.omit(indexSettings?.index, [
|
|
1376
|
-
"creation_date",
|
|
1377
|
-
"provided_name",
|
|
1378
|
-
"uuid",
|
|
1379
|
-
"version",
|
|
1380
|
-
]),
|
|
1381
|
-
};
|
|
1382
|
-
}
|
|
1383
|
-
/**
|
|
1384
|
-
* Sends an empty UpdateByQuery request to update the search index
|
|
1385
|
-
*
|
|
1386
|
-
* @param {String} index - Index name
|
|
1387
|
-
* @param {String} collection - Collection name
|
|
1388
|
-
* @returns {Promise.<Object>} {}
|
|
1389
|
-
*/
|
|
1390
|
-
async updateSearchIndex(index, collection) {
|
|
1391
|
-
const esRequest = {
|
|
1392
|
-
// @cluster: conflicts when two nodes start at the same time
|
|
1393
|
-
conflicts: "proceed",
|
|
1394
|
-
index: this._getAlias(index, collection),
|
|
1395
|
-
refresh: true,
|
|
1396
|
-
// This operation can take some time: this should be an ES
|
|
1397
|
-
// background task. And it's preferable to a request timeout when
|
|
1398
|
-
// processing large indexes.
|
|
1399
|
-
wait_for_completion: false,
|
|
1400
|
-
};
|
|
1401
|
-
this.logger.debug("UpdateByQuery: %o", esRequest);
|
|
1402
|
-
try {
|
|
1403
|
-
await this._client.updateByQuery(esRequest);
|
|
1404
|
-
}
|
|
1405
|
-
catch (error) {
|
|
1406
|
-
throw this._esWrapper.formatESError(error);
|
|
1407
|
-
}
|
|
1408
|
-
}
|
|
1409
|
-
/**
|
|
1410
|
-
* Update a collection mappings
|
|
1411
|
-
*
|
|
1412
|
-
* @param {String} index - Index name
|
|
1413
|
-
* @param {String} collection - Collection name
|
|
1414
|
-
* @param {Object} mappings - Collection mappings in ES format
|
|
1415
|
-
*
|
|
1416
|
-
* @returns {Promise.<{ dynamic, _meta, properties }>}
|
|
1417
|
-
*/
|
|
1418
|
-
async updateMapping(index, collection, mappings = {}) {
|
|
1419
|
-
let esRequest = {
|
|
1420
|
-
index: this._getAlias(index, collection),
|
|
1421
|
-
};
|
|
1422
|
-
this._checkDynamicProperty(mappings);
|
|
1423
|
-
const collectionMappings = await this.getMapping(index, collection, {
|
|
1424
|
-
includeKuzzleMeta: true,
|
|
1425
|
-
});
|
|
1426
|
-
this._checkMappings(mappings);
|
|
1427
|
-
const _meta = mappings._meta || collectionMappings._meta;
|
|
1428
|
-
const dynamic = mappings.dynamic || collectionMappings.dynamic;
|
|
1429
|
-
esRequest = {
|
|
1430
|
-
...esRequest,
|
|
1431
|
-
_meta,
|
|
1432
|
-
dynamic,
|
|
1433
|
-
properties: mappings.properties,
|
|
1434
|
-
};
|
|
1435
|
-
this.logger.debug("Update mapping: %o", esRequest);
|
|
1436
|
-
try {
|
|
1437
|
-
await this._client.indices.putMapping(esRequest);
|
|
1438
|
-
}
|
|
1439
|
-
catch (error) {
|
|
1440
|
-
throw this._esWrapper.formatESError(error);
|
|
1441
|
-
}
|
|
1442
|
-
const fullProperties = lodash_1.default.merge(collectionMappings.properties, mappings.properties);
|
|
1443
|
-
return {
|
|
1444
|
-
_meta,
|
|
1445
|
-
dynamic: dynamic?.toString(),
|
|
1446
|
-
properties: fullProperties,
|
|
1447
|
-
};
|
|
1448
|
-
}
|
|
1449
|
-
/**
|
|
1450
|
-
* Updates a collection settings (eg: analyzers)
|
|
1451
|
-
*
|
|
1452
|
-
* @param {String} index - Index name
|
|
1453
|
-
* @param {String} collection - Collection name
|
|
1454
|
-
* @param {Object} settings - Collection settings in ES format
|
|
1455
|
-
*
|
|
1456
|
-
* @returns {Promise}
|
|
1457
|
-
*/
|
|
1458
|
-
async updateSettings(index, collection, settings = {}) {
|
|
1459
|
-
const esRequest = {
|
|
1460
|
-
index: this._getAlias(index, collection),
|
|
1461
|
-
};
|
|
1462
|
-
await this._client.indices.close(esRequest);
|
|
1463
|
-
try {
|
|
1464
|
-
await this._client.indices.putSettings({ ...esRequest, body: settings });
|
|
1465
|
-
}
|
|
1466
|
-
catch (error) {
|
|
1467
|
-
throw this._esWrapper.formatESError(error);
|
|
1468
|
-
}
|
|
1469
|
-
finally {
|
|
1470
|
-
await this._client.indices.open(esRequest);
|
|
1471
|
-
}
|
|
1472
|
-
return null;
|
|
1473
|
-
}
|
|
1474
|
-
/**
|
|
1475
|
-
* Empties the content of a collection. Keep the existing mapping and settings.
|
|
1476
|
-
*
|
|
1477
|
-
* @param {String} index - Index name
|
|
1478
|
-
* @param {String} collection - Collection name
|
|
1479
|
-
*
|
|
1480
|
-
* @returns {Promise}
|
|
1481
|
-
*/
|
|
1482
|
-
async truncateCollection(index, collection) {
|
|
1483
|
-
let mappings;
|
|
1484
|
-
let settings;
|
|
1485
|
-
const esRequest = {
|
|
1486
|
-
index: await this._getIndice(index, collection),
|
|
1487
|
-
};
|
|
1488
|
-
try {
|
|
1489
|
-
mappings = await this.getMapping(index, collection, {
|
|
1490
|
-
includeKuzzleMeta: true,
|
|
1491
|
-
});
|
|
1492
|
-
settings = await this._getSettings(esRequest);
|
|
1493
|
-
settings = {
|
|
1494
|
-
...settings,
|
|
1495
|
-
...this.getAllowedIndexSettings(settings),
|
|
1496
|
-
};
|
|
1497
|
-
await this._client.indices.delete(esRequest);
|
|
1498
|
-
await this._client.indices.create({
|
|
1499
|
-
...esRequest,
|
|
1500
|
-
aliases: {
|
|
1501
|
-
[this._getAlias(index, collection)]: {},
|
|
1502
|
-
},
|
|
1503
|
-
mappings,
|
|
1504
|
-
settings,
|
|
1505
|
-
wait_for_active_shards: await this._getWaitForActiveShards(),
|
|
1506
|
-
});
|
|
1507
|
-
return null;
|
|
1508
|
-
}
|
|
1509
|
-
catch (error) {
|
|
1510
|
-
throw this._esWrapper.formatESError(error);
|
|
1511
|
-
}
|
|
1512
|
-
}
|
|
1513
|
-
/**
|
|
1514
|
-
* Runs several action and document
|
|
1515
|
-
*
|
|
1516
|
-
* @param {String} index - Index name
|
|
1517
|
-
* @param {String} collection - Collection name
|
|
1518
|
-
* @param {Object[]} documents - Documents to import
|
|
1519
|
-
* @param {Object} options - timeout (undefined), refresh (undefined), userId (null)
|
|
1520
|
-
*
|
|
1521
|
-
* @returns {Promise.<{ items, errors }>
|
|
1522
|
-
*/
|
|
1523
|
-
async import(index, collection, documents, { refresh, timeout, userId = null, } = {}) {
|
|
1524
|
-
const alias = this._getAlias(index, collection);
|
|
1525
|
-
const dateNow = Date.now();
|
|
1526
|
-
const esRequest = {
|
|
1527
|
-
operations: documents,
|
|
1528
|
-
refresh,
|
|
1529
|
-
timeout,
|
|
1530
|
-
};
|
|
1531
|
-
const kuzzleMeta = {
|
|
1532
|
-
created: {
|
|
1533
|
-
author: getKuid(userId),
|
|
1534
|
-
createdAt: dateNow,
|
|
1535
|
-
updatedAt: null,
|
|
1536
|
-
updater: null,
|
|
1537
|
-
},
|
|
1538
|
-
updated: {
|
|
1539
|
-
updatedAt: dateNow,
|
|
1540
|
-
updater: getKuid(userId),
|
|
1541
|
-
},
|
|
1542
|
-
};
|
|
1543
|
-
assertWellFormedRefresh(esRequest);
|
|
1544
|
-
this._scriptCheck(documents);
|
|
1545
|
-
this._setLastActionToKuzzleMeta(esRequest, alias, kuzzleMeta);
|
|
1546
|
-
let body;
|
|
1547
|
-
try {
|
|
1548
|
-
body = await this._client.bulk(esRequest);
|
|
1549
|
-
}
|
|
1550
|
-
catch (error) {
|
|
1551
|
-
throw this._esWrapper.formatESError(error);
|
|
1552
|
-
}
|
|
1553
|
-
const result = {
|
|
1554
|
-
errors: [],
|
|
1555
|
-
items: [],
|
|
1556
|
-
};
|
|
1557
|
-
let idx = 0;
|
|
1558
|
-
/**
|
|
1559
|
-
* @warning Critical code section
|
|
1560
|
-
*
|
|
1561
|
-
* bulk body can contain more than 10K elements
|
|
1562
|
-
*/
|
|
1563
|
-
for (const row of body.items) {
|
|
1564
|
-
// Elasticsearch answers exactly one action per row; a row carrying none
|
|
1565
|
-
// describes no document, so there is nothing to report on it.
|
|
1566
|
-
const [action = ""] = Object.keys(row);
|
|
1567
|
-
const item = Object.values(row)[0];
|
|
1568
|
-
if (item === undefined) {
|
|
1569
|
-
continue;
|
|
1570
|
-
}
|
|
1571
|
-
if (item.status >= 400) {
|
|
1572
|
-
result.errors.push({
|
|
1573
|
-
[action]: this._importError(action, item, documents[idx + 1]),
|
|
1574
|
-
});
|
|
1575
|
-
}
|
|
1576
|
-
else {
|
|
1577
|
-
result.items.push({
|
|
1578
|
-
[action]: {
|
|
1579
|
-
_id: item._id,
|
|
1580
|
-
status: item.status,
|
|
1581
|
-
},
|
|
1582
|
-
});
|
|
1583
|
-
}
|
|
1584
|
-
// the delete action is not followed by an action payload
|
|
1585
|
-
idx = action === "delete" ? idx + 1 : idx + 2;
|
|
1586
|
-
}
|
|
1587
|
-
/* end critical code section */
|
|
1588
|
-
return result;
|
|
1589
|
-
}
|
|
1590
|
-
/**
|
|
1591
|
-
* The error entry `import` reports for one rejected bulk row.
|
|
1592
|
-
*
|
|
1593
|
-
* @param action - the bulk action Elasticsearch echoed back
|
|
1594
|
-
* @param item - that action's answer
|
|
1595
|
-
* @param payload - the action's payload, absent for a delete
|
|
1596
|
-
*/
|
|
1597
|
-
_importError(action, item, payload) {
|
|
1598
|
-
const error = {
|
|
1599
|
-
_id: item._id,
|
|
1600
|
-
status: item.status,
|
|
1601
|
-
};
|
|
1602
|
-
// update action contain body in "doc" field
|
|
1603
|
-
// the delete action is not followed by an action payload
|
|
1604
|
-
if (action !== "delete") {
|
|
1605
|
-
const source = (action === "update" ? payload?.doc : payload) ?? {};
|
|
1606
|
-
source._kuzzle_info = undefined;
|
|
1607
|
-
error._source = source;
|
|
1608
|
-
}
|
|
1609
|
-
// ES response does not systematicaly include an error object
|
|
1610
|
-
// (e.g. delete action with 404 status)
|
|
1611
|
-
if (item.error) {
|
|
1612
|
-
error.error = {
|
|
1613
|
-
reason: item.error.reason ?? "",
|
|
1614
|
-
type: item.error.type,
|
|
1615
|
-
};
|
|
1616
|
-
}
|
|
1617
|
-
return error;
|
|
1618
|
-
}
|
|
1619
|
-
/**
|
|
1620
|
-
* Retrieves the complete list of existing collections in the current index
|
|
1621
|
-
*
|
|
1622
|
-
* @param {String} index - Index name
|
|
1623
|
-
* @param {Object.Boolean} includeHidden - Optional: include HIDDEN_COLLECTION in results
|
|
1624
|
-
*
|
|
1625
|
-
* @returns {Promise.<Array>} Collection names
|
|
1626
|
-
*/
|
|
1627
|
-
async listCollections(index, { includeHidden = false } = {}) {
|
|
1628
|
-
let body;
|
|
1629
|
-
try {
|
|
1630
|
-
body = await this._catAliases();
|
|
1631
|
-
}
|
|
1632
|
-
catch (error) {
|
|
1633
|
-
throw this._esWrapper.formatESError(error);
|
|
1634
|
-
}
|
|
1635
|
-
const aliases = body.map(({ alias }) => alias);
|
|
1636
|
-
const schema = this._extractSchema(aliases, { includeHidden });
|
|
1637
|
-
return schema[index] || [];
|
|
1638
|
-
}
|
|
1639
|
-
/**
|
|
1640
|
-
* Retrieves the complete list of indexes
|
|
1641
|
-
*
|
|
1642
|
-
* @returns {Promise.<Array>} Index names
|
|
1643
|
-
*/
|
|
1644
|
-
async listIndexes() {
|
|
1645
|
-
let body;
|
|
1646
|
-
try {
|
|
1647
|
-
body = await this._catAliases();
|
|
1648
|
-
}
|
|
1649
|
-
catch (error) {
|
|
1650
|
-
throw this._esWrapper.formatESError(error);
|
|
1651
|
-
}
|
|
1652
|
-
const aliases = body.map(({ alias }) => alias);
|
|
1653
|
-
const schema = this._extractSchema(aliases);
|
|
1654
|
-
return Object.keys(schema);
|
|
1655
|
-
}
|
|
1656
|
-
/**
|
|
1657
|
-
* Returns an object containing the list of indexes and collections
|
|
1658
|
-
*
|
|
1659
|
-
* @returns {Object.<String, String[]>} Object<index, collections>
|
|
1660
|
-
*/
|
|
1661
|
-
async getSchema() {
|
|
1662
|
-
let body;
|
|
1663
|
-
try {
|
|
1664
|
-
body = await this._catAliases();
|
|
1665
|
-
}
|
|
1666
|
-
catch (error) {
|
|
1667
|
-
throw this._esWrapper.formatESError(error);
|
|
1668
|
-
}
|
|
1669
|
-
const aliases = body.map(({ alias }) => alias);
|
|
1670
|
-
const schema = this._extractSchema(aliases, { includeHidden: true });
|
|
1671
|
-
for (const [index, collections] of Object.entries(schema)) {
|
|
1672
|
-
schema[index] = collections.filter((c) => c !== HIDDEN_COLLECTION);
|
|
1673
|
-
}
|
|
1674
|
-
return schema;
|
|
1675
|
-
}
|
|
1676
|
-
/**
|
|
1677
|
-
* Retrieves the complete list of aliases
|
|
1678
|
-
*
|
|
1679
|
-
* @returns {Promise.<Object[]>} [ { alias, index, collection, indice } ]
|
|
1680
|
-
*/
|
|
1681
|
-
async listAliases() {
|
|
1682
|
-
let body;
|
|
1683
|
-
try {
|
|
1684
|
-
body = await this._catAliases();
|
|
1685
|
-
}
|
|
1686
|
-
catch (error) {
|
|
1687
|
-
throw this._esWrapper.formatESError(error);
|
|
1688
|
-
}
|
|
1689
|
-
const aliases = [];
|
|
1690
|
-
for (const { alias, index: indice } of body) {
|
|
1691
|
-
if (alias[INDEX_PREFIX_POSITION_IN_ALIAS] === this._indexPrefix) {
|
|
1692
|
-
aliases.push({
|
|
1693
|
-
alias,
|
|
1694
|
-
collection: this._extractCollection(alias),
|
|
1695
|
-
index: this._extractIndex(alias),
|
|
1696
|
-
indice,
|
|
1697
|
-
});
|
|
1698
|
-
}
|
|
1699
|
-
}
|
|
1700
|
-
return aliases;
|
|
1701
|
-
}
|
|
1702
|
-
/**
|
|
1703
|
-
* Deletes a collection
|
|
1704
|
-
*
|
|
1705
|
-
* @param {String} index - Index name
|
|
1706
|
-
* @param {String} collection - Collection name
|
|
1707
|
-
*
|
|
1708
|
-
* @returns {Promise}
|
|
1709
|
-
*/
|
|
1710
|
-
async deleteCollection(index, collection) {
|
|
1711
|
-
const indice = await this._getIndice(index, collection);
|
|
1712
|
-
const esRequest = {
|
|
1713
|
-
index: indice,
|
|
1714
|
-
};
|
|
1715
|
-
try {
|
|
1716
|
-
await this._client.indices.delete(esRequest);
|
|
1717
|
-
const alias = this._getAlias(index, collection);
|
|
1718
|
-
if (await this._checkIfAliasExists(alias)) {
|
|
1719
|
-
await this._client.indices.deleteAlias({
|
|
1720
|
-
index: indice,
|
|
1721
|
-
name: alias,
|
|
1722
|
-
});
|
|
1723
|
-
}
|
|
1724
|
-
// `createCollection` drops the placeholder through here: recreating it
|
|
1725
|
-
// would undo that.
|
|
1726
|
-
if (collection !== HIDDEN_COLLECTION) {
|
|
1727
|
-
await this._createHiddenCollection(index);
|
|
1728
|
-
}
|
|
1729
|
-
}
|
|
1730
|
-
catch (e) {
|
|
1731
|
-
throw this._esWrapper.formatESError(e);
|
|
1732
|
-
}
|
|
1733
|
-
return null;
|
|
1734
|
-
}
|
|
1735
|
-
/**
|
|
1736
|
-
* Deletes multiple indexes
|
|
1737
|
-
*
|
|
1738
|
-
* @param {String[]} indexes - Index names
|
|
1739
|
-
*
|
|
1740
|
-
* @returns {Promise.<String[]>}
|
|
1741
|
-
*/
|
|
1742
|
-
async deleteIndexes(indexes = []) {
|
|
1743
|
-
if (indexes.length === 0) {
|
|
1744
|
-
return bluebird_1.default.resolve([]);
|
|
1745
|
-
}
|
|
1746
|
-
const deleted = new Set();
|
|
1747
|
-
try {
|
|
1748
|
-
const body = await this._catAliases();
|
|
1749
|
-
const esRequest = body.reduce((request, { alias, index: indice }) => {
|
|
1750
|
-
const index = this._extractIndex(alias);
|
|
1751
|
-
if (alias[INDEX_PREFIX_POSITION_IN_ALIAS] !== this._indexPrefix ||
|
|
1752
|
-
!indexes.includes(index)) {
|
|
1753
|
-
return request;
|
|
1754
|
-
}
|
|
1755
|
-
deleted.add(index);
|
|
1756
|
-
request.index.push(indice);
|
|
1757
|
-
return request;
|
|
1758
|
-
}, { index: [] });
|
|
1759
|
-
if (esRequest.index.length === 0) {
|
|
1760
|
-
return [];
|
|
1761
|
-
}
|
|
1762
|
-
this.logger.debug("Delete indexes: %o", esRequest);
|
|
1763
|
-
await this._client.indices.delete(esRequest);
|
|
1764
|
-
}
|
|
1765
|
-
catch (error) {
|
|
1766
|
-
throw this._esWrapper.formatESError(error);
|
|
1767
|
-
}
|
|
1768
|
-
return Array.from(deleted);
|
|
1769
|
-
}
|
|
1770
|
-
/**
|
|
1771
|
-
* Deletes an index
|
|
1772
|
-
*
|
|
1773
|
-
* @param {String} index - Index name
|
|
1774
|
-
*
|
|
1775
|
-
* @returns {Promise}
|
|
1776
|
-
*/
|
|
1777
|
-
async deleteIndex(index) {
|
|
1778
|
-
await this.deleteIndexes([index]);
|
|
1779
|
-
return null;
|
|
1780
|
-
}
|
|
1781
|
-
/**
|
|
1782
|
-
* Forces a refresh on the collection.
|
|
1783
|
-
*
|
|
1784
|
-
* /!\ Can lead to some performance issues.
|
|
1785
|
-
* cf https://www.elastic.co/guide/en/elasticsearch/guide/current/near-real-time.html for more details
|
|
1786
|
-
*
|
|
1787
|
-
* @param {String} index - Index name
|
|
1788
|
-
* @param {String} collection - Collection name
|
|
1789
|
-
*
|
|
1790
|
-
* @returns {Promise.<Object>} { _shards }
|
|
1791
|
-
*/
|
|
1792
|
-
async refreshCollection(index, collection) {
|
|
1793
|
-
const esRequest = {
|
|
1794
|
-
index: this._getAlias(index, collection),
|
|
1795
|
-
};
|
|
1796
|
-
let body;
|
|
1797
|
-
try {
|
|
1798
|
-
body = await this._client.indices.refresh(esRequest);
|
|
1799
|
-
}
|
|
1800
|
-
catch (error) {
|
|
1801
|
-
throw this._esWrapper.formatESError(error);
|
|
1802
|
-
}
|
|
1803
|
-
return body;
|
|
1804
|
-
}
|
|
1805
|
-
/**
|
|
1806
|
-
* Returns true if the document exists
|
|
1807
|
-
*
|
|
1808
|
-
* @param {String} index - Index name
|
|
1809
|
-
* @param {String} collection - Collection name
|
|
1810
|
-
* @param {String} id - Document ID
|
|
1811
|
-
*
|
|
1812
|
-
* @returns {Promise.<boolean>}
|
|
1813
|
-
*/
|
|
1814
|
-
async exists(index, collection, id) {
|
|
1815
|
-
const esRequest = {
|
|
1816
|
-
id,
|
|
1817
|
-
index: this._getAlias(index, collection),
|
|
1818
|
-
};
|
|
1819
|
-
try {
|
|
1820
|
-
return await this._client.exists(esRequest);
|
|
1821
|
-
}
|
|
1822
|
-
catch (error) {
|
|
1823
|
-
throw this._esWrapper.formatESError(error);
|
|
1824
|
-
}
|
|
1825
|
-
}
|
|
1826
|
-
/**
|
|
1827
|
-
* Returns the list of documents existing with the ids given in the body param
|
|
1828
|
-
* NB: Due to internal Kuzzle mechanism, can only be called on a single
|
|
1829
|
-
* index/collection, using the body { ids: [.. } syntax.
|
|
1830
|
-
*
|
|
1831
|
-
* @param {String} index - Index name
|
|
1832
|
-
* @param {String} collection - Collection name
|
|
1833
|
-
* @param {Array.<String>} ids - Document IDs
|
|
1834
|
-
*
|
|
1835
|
-
* @returns {Promise.<{ items: Array<{ _id, _source, _version }>, errors }>}
|
|
1836
|
-
*/
|
|
1837
|
-
async mExists(index, collection, ids) {
|
|
1838
|
-
if (ids.length === 0) {
|
|
1839
|
-
return { errors: [], items: [] };
|
|
1840
|
-
}
|
|
1841
|
-
const esRequest = {
|
|
1842
|
-
_source: "false",
|
|
1843
|
-
docs: ids.map((_id) => ({ _id })),
|
|
1844
|
-
index: this._getAlias(index, collection),
|
|
1845
|
-
};
|
|
1846
|
-
this.logger.debug("mExists: %o", esRequest);
|
|
1847
|
-
let body;
|
|
1848
|
-
try {
|
|
1849
|
-
body = await this._client.mget(esRequest); // NOSONAR
|
|
1850
|
-
}
|
|
1851
|
-
catch (e) {
|
|
1852
|
-
throw this._esWrapper.formatESError(e);
|
|
1853
|
-
}
|
|
1854
|
-
const errors = [];
|
|
1855
|
-
const items = [];
|
|
1856
|
-
for (const doc of body.docs) {
|
|
1857
|
-
if (!("error" in doc) && doc.found) {
|
|
1858
|
-
items.push(doc._id);
|
|
1859
|
-
}
|
|
1860
|
-
else {
|
|
1861
|
-
errors.push(doc._id);
|
|
1862
|
-
}
|
|
1863
|
-
}
|
|
1864
|
-
return { errors, items };
|
|
1865
|
-
}
|
|
1866
|
-
/**
|
|
1867
|
-
* Returns true if the index exists
|
|
1868
|
-
*
|
|
1869
|
-
* @param {String} index - Index name
|
|
1870
|
-
*
|
|
1871
|
-
* @returns {Promise.<boolean>}
|
|
1872
|
-
*/
|
|
1873
|
-
async hasIndex(index) {
|
|
1874
|
-
const indexes = await this.listIndexes();
|
|
1875
|
-
return indexes.some((idx) => idx === index);
|
|
1876
|
-
}
|
|
1877
|
-
/**
|
|
1878
|
-
* Returns true if the collection exists
|
|
1879
|
-
*
|
|
1880
|
-
* @param {String} index - Index name
|
|
1881
|
-
* @param {String} collection - Collection name
|
|
1882
|
-
*
|
|
1883
|
-
* @returns {Promise.<boolean>}
|
|
1884
|
-
*/
|
|
1885
|
-
async hasCollection(index, collection) {
|
|
1886
|
-
const collections = await this.listCollections(index);
|
|
1887
|
-
return collections.some((col) => col === collection);
|
|
1888
|
-
}
|
|
1889
|
-
/**
|
|
1890
|
-
* Returns true if the index has the hidden collection
|
|
1891
|
-
*
|
|
1892
|
-
* @param {String} index - Index name
|
|
1893
|
-
*
|
|
1894
|
-
* @returns {Promise.<boolean>}
|
|
1895
|
-
*/
|
|
1896
|
-
async _hasHiddenCollection(index) {
|
|
1897
|
-
const collections = await this.listCollections(index, {
|
|
1898
|
-
includeHidden: true,
|
|
1899
|
-
});
|
|
1900
|
-
return collections.includes(HIDDEN_COLLECTION);
|
|
1901
|
-
}
|
|
1902
|
-
/**
|
|
1903
|
-
* Creates multiple documents at once.
|
|
1904
|
-
* If a content has no id, one is automatically generated and assigned to it.
|
|
1905
|
-
* If a content has a specified identifier, it is rejected if it already exists
|
|
1906
|
-
*
|
|
1907
|
-
* @param {String} index - Index name
|
|
1908
|
-
* @param {String} collection - Collection name
|
|
1909
|
-
* @param {Object[]} documents - Documents
|
|
1910
|
-
* @param {Object} options - timeout (undefined), refresh (undefined), userId (null)
|
|
1911
|
-
*
|
|
1912
|
-
* @returns {Promise.<Object>} { items, errors }
|
|
1913
|
-
*/
|
|
1914
|
-
async mCreate(index, collection, documents, { refresh, timeout, userId = null, } = {}) {
|
|
1915
|
-
const alias = this._getAlias(index, collection), kuzzleMeta = {
|
|
1916
|
-
_kuzzle_info: {
|
|
1917
|
-
author: getKuid(userId),
|
|
1918
|
-
createdAt: Date.now(),
|
|
1919
|
-
updatedAt: null,
|
|
1920
|
-
updater: null,
|
|
1921
|
-
},
|
|
1922
|
-
}, { rejected, extractedDocuments, documentsToGet } = this._extractMDocuments(documents, kuzzleMeta, { prepareMGet: true });
|
|
1923
|
-
// prepare the mget request, but only for document having a specified id
|
|
1924
|
-
const body = documentsToGet.length > 0
|
|
1925
|
-
? await this._client.mget({
|
|
1926
|
-
docs: documentsToGet,
|
|
1927
|
-
index: alias,
|
|
1928
|
-
})
|
|
1929
|
-
: { docs: [] };
|
|
1930
|
-
const existingDocuments = body.docs;
|
|
1931
|
-
const operations = [];
|
|
1932
|
-
const esRequest = {
|
|
1933
|
-
index: alias,
|
|
1934
|
-
operations,
|
|
1935
|
-
refresh,
|
|
1936
|
-
timeout,
|
|
1937
|
-
};
|
|
1938
|
-
const toImport = [];
|
|
1939
|
-
/**
|
|
1940
|
-
* @warning Critical code section
|
|
1941
|
-
*
|
|
1942
|
-
* request can contain more than 10K elements
|
|
1943
|
-
*/
|
|
1944
|
-
let idx = 0;
|
|
1945
|
-
for (const document of extractedDocuments) {
|
|
1946
|
-
const doc = existingDocuments[idx];
|
|
1947
|
-
// Documents are retrieved in the same order than we got them from user
|
|
1948
|
-
if (typeof document._id === "string" && doc !== undefined) {
|
|
1949
|
-
if (!("error" in doc) && doc.found) {
|
|
1950
|
-
document._source._kuzzle_info = undefined;
|
|
1951
|
-
rejected.push({
|
|
1952
|
-
document: {
|
|
1953
|
-
_id: document._id,
|
|
1954
|
-
body: document._source,
|
|
1955
|
-
},
|
|
1956
|
-
reason: "document already exists",
|
|
1957
|
-
status: 400,
|
|
1958
|
-
});
|
|
1959
|
-
}
|
|
1960
|
-
else {
|
|
1961
|
-
operations.push({
|
|
1962
|
-
index: {
|
|
1963
|
-
_id: document._id,
|
|
1964
|
-
_index: alias,
|
|
1965
|
-
},
|
|
1966
|
-
}, document._source);
|
|
1967
|
-
toImport.push(document);
|
|
1968
|
-
}
|
|
1969
|
-
idx++;
|
|
1970
|
-
}
|
|
1971
|
-
else {
|
|
1972
|
-
operations.push({ index: { _index: alias } }, document._source);
|
|
1973
|
-
toImport.push(document);
|
|
1974
|
-
}
|
|
1975
|
-
}
|
|
1976
|
-
/* end critical code section */
|
|
1977
|
-
return this._mExecute(esRequest, toImport, rejected);
|
|
1978
|
-
}
|
|
1979
|
-
/**
|
|
1980
|
-
* Creates or replaces multiple documents at once.
|
|
1981
|
-
*
|
|
1982
|
-
* @param {String} index - Index name
|
|
1983
|
-
* @param {String} collection - Collection name
|
|
1984
|
-
* @param {Object[]} documents - Documents
|
|
1985
|
-
* @param {Object} options - timeout (undefined), refresh (undefined), userId (null), injectKuzzleMeta (false), limits (true)
|
|
1986
|
-
*
|
|
1987
|
-
* @returns {Promise.<{ items, errors }>
|
|
1988
|
-
*/
|
|
1989
|
-
async mCreateOrReplace(index, collection, documents, { refresh, timeout, userId = null, injectKuzzleMeta = true, limits = true, source = true, } = {}) {
|
|
1990
|
-
let kuzzleMeta = {};
|
|
1991
|
-
if (injectKuzzleMeta) {
|
|
1992
|
-
kuzzleMeta = {
|
|
1993
|
-
_kuzzle_info: {
|
|
1994
|
-
author: getKuid(userId),
|
|
1995
|
-
createdAt: Date.now(),
|
|
1996
|
-
updatedAt: null,
|
|
1997
|
-
updater: null,
|
|
1998
|
-
},
|
|
1999
|
-
};
|
|
2000
|
-
}
|
|
2001
|
-
const alias = this._getAlias(index, collection);
|
|
2002
|
-
const operations = [];
|
|
2003
|
-
const esRequest = {
|
|
2004
|
-
index: alias,
|
|
2005
|
-
operations,
|
|
2006
|
-
refresh,
|
|
2007
|
-
timeout,
|
|
2008
|
-
};
|
|
2009
|
-
const { rejected, extractedDocuments } = this._extractMDocuments(documents, kuzzleMeta);
|
|
2010
|
-
/**
|
|
2011
|
-
* @warning Critical code section
|
|
2012
|
-
*
|
|
2013
|
-
* request can contain more than 10K elements
|
|
2014
|
-
*/
|
|
2015
|
-
for (const extractedDocument of extractedDocuments) {
|
|
2016
|
-
operations.push({
|
|
2017
|
-
index: {
|
|
2018
|
-
_id: extractedDocument._id,
|
|
2019
|
-
_index: alias,
|
|
2020
|
-
},
|
|
2021
|
-
}, extractedDocument._source);
|
|
2022
|
-
}
|
|
2023
|
-
/* end critical code section */
|
|
2024
|
-
return this._mExecute(esRequest, extractedDocuments, rejected, {
|
|
2025
|
-
limits,
|
|
2026
|
-
source,
|
|
2027
|
-
});
|
|
2028
|
-
}
|
|
2029
|
-
/**
|
|
2030
|
-
* Updates multiple documents with one request
|
|
2031
|
-
* Replacements are rejected if targeted documents do not exist
|
|
2032
|
-
* (like with the normal "update" method)
|
|
2033
|
-
*
|
|
2034
|
-
* @param {String} index - Index name
|
|
2035
|
-
* @param {String} collection - Collection name
|
|
2036
|
-
* @param {Object[]} documents - Documents
|
|
2037
|
-
* @param {Object} options - timeout (undefined), refresh (undefined), retryOnConflict (0), userId (null)
|
|
2038
|
-
*
|
|
2039
|
-
* @returns {Promise.<Object>} { items, errors }
|
|
2040
|
-
*/
|
|
2041
|
-
async mUpdate(index, collection, documents, { refresh, retryOnConflict = 0, timeout, userId = null, } = {}) {
|
|
2042
|
-
const operations = [];
|
|
2043
|
-
const alias = this._getAlias(index, collection), toImport = [], esRequest = {
|
|
2044
|
-
index: alias,
|
|
2045
|
-
operations,
|
|
2046
|
-
refresh,
|
|
2047
|
-
timeout,
|
|
2048
|
-
}, kuzzleMeta = {
|
|
2049
|
-
_kuzzle_info: {
|
|
2050
|
-
updatedAt: Date.now(),
|
|
2051
|
-
updater: getKuid(userId),
|
|
2052
|
-
},
|
|
2053
|
-
}, { rejected, extractedDocuments } = this._extractMDocuments(documents, kuzzleMeta);
|
|
2054
|
-
/**
|
|
2055
|
-
* @warning Critical code section
|
|
2056
|
-
*
|
|
2057
|
-
* request can contain more than 10K elements
|
|
2058
|
-
*/
|
|
2059
|
-
for (const extractedDocument of extractedDocuments) {
|
|
2060
|
-
if (typeof extractedDocument._id === "string") {
|
|
2061
|
-
operations.push({
|
|
2062
|
-
update: {
|
|
2063
|
-
_id: extractedDocument._id,
|
|
2064
|
-
_index: alias,
|
|
2065
|
-
retry_on_conflict: retryOnConflict ||
|
|
2066
|
-
this._config.defaults.onUpdateConflictRetries,
|
|
2067
|
-
},
|
|
2068
|
-
},
|
|
2069
|
-
// _source: true => makes ES return the updated document source in
|
|
2070
|
-
// the response. Required by the real-time notifier component
|
|
2071
|
-
{
|
|
2072
|
-
_source: true,
|
|
2073
|
-
doc: extractedDocument._source,
|
|
2074
|
-
});
|
|
2075
|
-
toImport.push(extractedDocument);
|
|
2076
|
-
}
|
|
2077
|
-
else {
|
|
2078
|
-
extractedDocument._source._kuzzle_info = undefined;
|
|
2079
|
-
rejected.push({
|
|
2080
|
-
document: {
|
|
2081
|
-
_id: extractedDocument._id,
|
|
2082
|
-
body: extractedDocument._source,
|
|
2083
|
-
},
|
|
2084
|
-
reason: "document _id must be a string",
|
|
2085
|
-
status: 400,
|
|
2086
|
-
});
|
|
2087
|
-
}
|
|
2088
|
-
}
|
|
2089
|
-
/* end critical code section */
|
|
2090
|
-
const response = await this._mExecute(esRequest, toImport, rejected);
|
|
2091
|
-
// with _source: true, ES returns the updated document in
|
|
2092
|
-
// response.result.get._source
|
|
2093
|
-
// => we replace response.result._source with it so that the notifier
|
|
2094
|
-
// module can seamlessly process all kind of m* response*
|
|
2095
|
-
response.items = response.items.map((item) => ({
|
|
2096
|
-
_id: item._id,
|
|
2097
|
-
_source: item.get._source,
|
|
2098
|
-
_version: item._version,
|
|
2099
|
-
status: item.status,
|
|
2100
|
-
}));
|
|
2101
|
-
return response;
|
|
2102
|
-
}
|
|
2103
|
-
/**
|
|
2104
|
-
* Creates or replaces multiple documents at once.
|
|
2105
|
-
*
|
|
2106
|
-
* @param {String} index - Index name
|
|
2107
|
-
* @param {String} collection - Collection name
|
|
2108
|
-
* @param {Object[]} documents - Documents
|
|
2109
|
-
* @param {Object} options - refresh (undefined), retryOnConflict (0), timeout (undefined), userId (null)
|
|
2110
|
-
*
|
|
2111
|
-
* @returns {Promise.<{ items, errors }>
|
|
2112
|
-
*/
|
|
2113
|
-
async mUpsert(index, collection, documents, { refresh, retryOnConflict = 0, timeout, userId = null, } = {}) {
|
|
2114
|
-
const alias = this._getAlias(index, collection);
|
|
2115
|
-
const operations = [];
|
|
2116
|
-
const esRequest = {
|
|
2117
|
-
operations,
|
|
2118
|
-
refresh,
|
|
2119
|
-
timeout,
|
|
2120
|
-
};
|
|
2121
|
-
const user = getKuid(userId);
|
|
2122
|
-
const now = Date.now();
|
|
2123
|
-
const kuzzleMeta = {
|
|
2124
|
-
doc: {
|
|
2125
|
-
_kuzzle_info: {
|
|
2126
|
-
updatedAt: now,
|
|
2127
|
-
updater: user,
|
|
2128
|
-
},
|
|
2129
|
-
},
|
|
2130
|
-
upsert: {
|
|
2131
|
-
_kuzzle_info: {
|
|
2132
|
-
author: user,
|
|
2133
|
-
createdAt: now,
|
|
2134
|
-
},
|
|
2135
|
-
},
|
|
2136
|
-
};
|
|
2137
|
-
const { rejected, extractedDocuments } = this._extractMDocuments(documents, kuzzleMeta, {
|
|
2138
|
-
prepareMUpsert: true,
|
|
2139
|
-
requireId: true,
|
|
2140
|
-
});
|
|
2141
|
-
/**
|
|
2142
|
-
* @warning Critical code section
|
|
2143
|
-
*
|
|
2144
|
-
* request can contain more than 10K elements
|
|
2145
|
-
*/
|
|
2146
|
-
for (const extractedDocument of extractedDocuments) {
|
|
2147
|
-
operations.push({
|
|
2148
|
-
update: {
|
|
2149
|
-
_id: extractedDocument._id,
|
|
2150
|
-
_index: alias,
|
|
2151
|
-
_source: true,
|
|
2152
|
-
retry_on_conflict: retryOnConflict || this._config.defaults.onUpdateConflictRetries,
|
|
2153
|
-
},
|
|
2154
|
-
}, {
|
|
2155
|
-
doc: extractedDocument._source.changes,
|
|
2156
|
-
upsert: extractedDocument._source.default,
|
|
2157
|
-
});
|
|
2158
|
-
// _source: true
|
|
2159
|
-
// Makes ES return the updated document source in the response.
|
|
2160
|
-
// Required by the real-time notifier component
|
|
2161
|
-
}
|
|
2162
|
-
/* end critical code section */
|
|
2163
|
-
const response = await this._mExecute(esRequest, extractedDocuments, rejected);
|
|
2164
|
-
// with _source: true, ES returns the updated document in
|
|
2165
|
-
// response.result.get._source
|
|
2166
|
-
// => we replace response.result._source with it so that the notifier
|
|
2167
|
-
// module can seamlessly process all kind of m* response*
|
|
2168
|
-
response.items = response.items.map((item) => ({
|
|
2169
|
-
_id: item._id,
|
|
2170
|
-
_source: item.get._source,
|
|
2171
|
-
_version: item._version,
|
|
2172
|
-
created: item.result === "created", // Needed by the notifier
|
|
2173
|
-
status: item.status,
|
|
2174
|
-
}));
|
|
2175
|
-
return response;
|
|
2176
|
-
}
|
|
2177
|
-
/**
|
|
2178
|
-
* Replaces multiple documents at once.
|
|
2179
|
-
* Replacements are rejected if targeted documents do not exist
|
|
2180
|
-
* (like with the normal "replace" method)
|
|
2181
|
-
*
|
|
2182
|
-
* @param {String} index - Index name
|
|
2183
|
-
* @param {String} collection - Collection name
|
|
2184
|
-
* @param {Object[]} documents - Documents
|
|
2185
|
-
* @param {Object} options - timeout (undefined), refresh (undefined), userId (null)
|
|
2186
|
-
*
|
|
2187
|
-
* @returns {Promise.<Object>} { items, errors }
|
|
2188
|
-
*/
|
|
2189
|
-
async mReplace(index, collection, documents, { refresh, timeout, userId = null, } = {}) {
|
|
2190
|
-
const alias = this._getAlias(index, collection), kuzzleMeta = {
|
|
2191
|
-
_kuzzle_info: {
|
|
2192
|
-
author: getKuid(userId),
|
|
2193
|
-
createdAt: Date.now(),
|
|
2194
|
-
updatedAt: null,
|
|
2195
|
-
updater: null,
|
|
2196
|
-
},
|
|
2197
|
-
}, { rejected, extractedDocuments, documentsToGet } = this._extractMDocuments(documents, kuzzleMeta, {
|
|
2198
|
-
prepareMGet: true,
|
|
2199
|
-
requireId: true,
|
|
2200
|
-
});
|
|
2201
|
-
if (documentsToGet.length < 1) {
|
|
2202
|
-
return { errors: rejected, items: [] };
|
|
2203
|
-
}
|
|
2204
|
-
const body = await this._client.mget({
|
|
2205
|
-
docs: documentsToGet,
|
|
2206
|
-
index: alias,
|
|
2207
|
-
});
|
|
2208
|
-
const existingDocuments = body.docs;
|
|
2209
|
-
const operations = [];
|
|
2210
|
-
const esRequest = {
|
|
2211
|
-
operations,
|
|
2212
|
-
refresh,
|
|
2213
|
-
timeout,
|
|
2214
|
-
};
|
|
2215
|
-
const toImport = [];
|
|
2216
|
-
/**
|
|
2217
|
-
* @warning Critical code section
|
|
2218
|
-
*
|
|
2219
|
-
* request can contain more than 10K elements
|
|
2220
|
-
*/
|
|
2221
|
-
for (const [i, document] of extractedDocuments.entries()) {
|
|
2222
|
-
// Documents are retrieved in the same order than we got them from user
|
|
2223
|
-
const doc = existingDocuments[i];
|
|
2224
|
-
// `doc` used to be read with `"error" in doc` and only then with `?.`:
|
|
2225
|
-
// a shorter mget answer than the request reached the `in` first, which
|
|
2226
|
-
// throws on undefined.
|
|
2227
|
-
if (doc !== undefined && !("error" in doc) && doc.found) {
|
|
2228
|
-
operations.push({
|
|
2229
|
-
index: {
|
|
2230
|
-
_id: document._id,
|
|
2231
|
-
_index: alias,
|
|
2232
|
-
},
|
|
2233
|
-
}, document._source);
|
|
2234
|
-
toImport.push(document);
|
|
2235
|
-
}
|
|
2236
|
-
else {
|
|
2237
|
-
document._source._kuzzle_info = undefined;
|
|
2238
|
-
rejected.push({
|
|
2239
|
-
document: {
|
|
2240
|
-
_id: document._id,
|
|
2241
|
-
body: document._source,
|
|
2242
|
-
},
|
|
2243
|
-
reason: "document not found",
|
|
2244
|
-
status: 404,
|
|
2245
|
-
});
|
|
2246
|
-
}
|
|
2247
|
-
}
|
|
2248
|
-
/* end critical code section */
|
|
2249
|
-
return this._mExecute(esRequest, toImport, rejected);
|
|
2250
|
-
}
|
|
2251
|
-
/**
|
|
2252
|
-
* Deletes multiple documents with one request
|
|
2253
|
-
*
|
|
2254
|
-
* @param {String} index - Index name
|
|
2255
|
-
* @param {String} collection - Collection name
|
|
2256
|
-
* @param {Array.<String>} ids - Documents IDs
|
|
2257
|
-
* @param {Object} options - timeout (undefined), refresh (undefined)
|
|
2258
|
-
*
|
|
2259
|
-
* @returns {Promise.<{ documents, errors }>
|
|
2260
|
-
*/
|
|
2261
|
-
async mDelete(index, collection, ids, { refresh, } = {}) {
|
|
2262
|
-
const query = { ids: { values: [] } };
|
|
2263
|
-
const validIds = [];
|
|
2264
|
-
const partialErrors = [];
|
|
2265
|
-
/**
|
|
2266
|
-
* @warning Critical code section
|
|
2267
|
-
*
|
|
2268
|
-
* request can contain more than 10K elements
|
|
2269
|
-
*/
|
|
2270
|
-
for (const _id of ids) {
|
|
2271
|
-
if (typeof _id === "string") {
|
|
2272
|
-
validIds.push(_id);
|
|
2273
|
-
}
|
|
2274
|
-
else {
|
|
2275
|
-
partialErrors.push({
|
|
2276
|
-
_id,
|
|
2277
|
-
reason: "document _id must be a string",
|
|
2278
|
-
status: 400,
|
|
2279
|
-
});
|
|
2280
|
-
}
|
|
2281
|
-
}
|
|
2282
|
-
/* end critical code section */
|
|
2283
|
-
await this.refreshCollection(index, collection);
|
|
2284
|
-
const { items } = await this.mGet(index, collection, validIds);
|
|
2285
|
-
let idx = 0;
|
|
2286
|
-
/**
|
|
2287
|
-
* @warning Critical code section
|
|
2288
|
-
*
|
|
2289
|
-
* request can contain more than 10K elements
|
|
2290
|
-
*/
|
|
2291
|
-
for (const validId of validIds) {
|
|
2292
|
-
const item = items[idx];
|
|
2293
|
-
if (item && item._id === validId) {
|
|
2294
|
-
query.ids.values.push(validId);
|
|
2295
|
-
idx++;
|
|
2296
|
-
}
|
|
2297
|
-
else {
|
|
2298
|
-
partialErrors.push({
|
|
2299
|
-
_id: validId,
|
|
2300
|
-
reason: "document not found",
|
|
2301
|
-
status: 404,
|
|
2302
|
-
});
|
|
2303
|
-
}
|
|
2304
|
-
}
|
|
2305
|
-
/* end critical code section */
|
|
2306
|
-
// @todo duplicated query to get documents body, mGet here and search in
|
|
2307
|
-
// deleteByQuery
|
|
2308
|
-
const { documents } = await this.deleteByQuery(index, collection, query, {
|
|
2309
|
-
refresh,
|
|
2310
|
-
});
|
|
2311
|
-
return { documents, errors: partialErrors };
|
|
2312
|
-
}
|
|
2313
|
-
/**
|
|
2314
|
-
* Executes an ES request prepared by mcreate, mupdate, mreplace, mdelete or mwriteDocuments
|
|
2315
|
-
* Returns a standardized ES response object, containing the list of
|
|
2316
|
-
* successfully performed operations, and the rejected ones
|
|
2317
|
-
*
|
|
2318
|
-
* @param {Object} esRequest - Elasticsearch request
|
|
2319
|
-
* @param {Object[]} documents - Document sources (format: {_id, _source})
|
|
2320
|
-
* @param {Object[]} partialErrors - pre-rejected documents
|
|
2321
|
-
* @param {Object} options - limits (true)
|
|
2322
|
-
*
|
|
2323
|
-
* @returns {Promise.<Object[]>} results
|
|
2324
|
-
*/
|
|
2325
|
-
async _mExecute(esRequest, documents, partialErrors = [], { limits = true, source = true } = {}) {
|
|
2326
|
-
assertWellFormedRefresh(esRequest);
|
|
2327
|
-
if (this._hasExceededLimit(limits, documents)) {
|
|
2328
|
-
return kerror.reject("services", "storage", "write_limit_exceeded");
|
|
2329
|
-
}
|
|
2330
|
-
let items = [];
|
|
2331
|
-
if (documents.length > 0) {
|
|
2332
|
-
try {
|
|
2333
|
-
({ items } = await this._client.bulk(esRequest));
|
|
2334
|
-
}
|
|
2335
|
-
catch (error) {
|
|
2336
|
-
throw this._esWrapper.formatESError(error);
|
|
2337
|
-
}
|
|
2338
|
-
}
|
|
2339
|
-
const successes = [];
|
|
2340
|
-
/**
|
|
2341
|
-
* @warning Critical code section
|
|
2342
|
-
*
|
|
2343
|
-
* request can contain more than 10K elements
|
|
2344
|
-
*/
|
|
2345
|
-
for (const [i, item] of items.entries()) {
|
|
2346
|
-
const result = Object.values(item)[0];
|
|
2347
|
-
const document = documents[i];
|
|
2348
|
-
// An answer carries exactly one result per document sent; a row without
|
|
2349
|
-
// its counterpart is one neither branch below could describe.
|
|
2350
|
-
if (result === undefined || document === undefined) {
|
|
2351
|
-
continue;
|
|
2352
|
-
}
|
|
2353
|
-
if (result.status >= 400) {
|
|
2354
|
-
partialErrors.push(this._mExecuteRejection(result, document));
|
|
2355
|
-
}
|
|
2356
|
-
else {
|
|
2357
|
-
successes.push({
|
|
2358
|
-
_id: result._id,
|
|
2359
|
-
_source: source ? document._source : undefined,
|
|
2360
|
-
_version: result._version,
|
|
2361
|
-
created: result.result === "created",
|
|
2362
|
-
get: result.get,
|
|
2363
|
-
result: result.result,
|
|
2364
|
-
status: result.status, // used by mUpdate to get the full document body
|
|
2365
|
-
});
|
|
2366
|
-
}
|
|
2367
|
-
}
|
|
2368
|
-
/* end critical code section */
|
|
2369
|
-
return {
|
|
2370
|
-
errors: partialErrors, // @todo rename items to documents
|
|
2371
|
-
items: successes,
|
|
2372
|
-
};
|
|
2373
|
-
}
|
|
2374
|
-
/**
|
|
2375
|
-
* The partial-error entry `_mExecute` reports for one rejected bulk row.
|
|
2376
|
-
*
|
|
2377
|
-
* A 404 answers no reason of its own, and reports the document by id and
|
|
2378
|
-
* body rather than whole, which is what the m* callers read back.
|
|
2379
|
-
*/
|
|
2380
|
-
_mExecuteRejection(result, document) {
|
|
2381
|
-
if (result.status === 404) {
|
|
2382
|
-
return {
|
|
2383
|
-
document: {
|
|
2384
|
-
_id: document._id,
|
|
2385
|
-
body: document._source,
|
|
2386
|
-
},
|
|
2387
|
-
reason: "document not found",
|
|
2388
|
-
status: result.status,
|
|
2389
|
-
};
|
|
2390
|
-
}
|
|
2391
|
-
return {
|
|
2392
|
-
document,
|
|
2393
|
-
reason: result.error?.reason,
|
|
2394
|
-
status: result.status,
|
|
2395
|
-
};
|
|
2396
|
-
}
|
|
2397
|
-
/**
|
|
2398
|
-
* Extracts, injects metadata and validates documents contained
|
|
2399
|
-
* in a Request
|
|
2400
|
-
*
|
|
2401
|
-
* Used by mCreate, mUpdate, mUpsert, mReplace, mCreateOrReplace and mWrite
|
|
2402
|
-
*
|
|
2403
|
-
* @param {Object[]} documents - Documents
|
|
2404
|
-
* @param {Object} metadata - Kuzzle metadata
|
|
2405
|
-
* @param {Object} options - prepareMGet (false), requireId (false)
|
|
2406
|
-
*
|
|
2407
|
-
* @returns {Object} { rejected, extractedDocuments, documentsToGet }
|
|
2408
|
-
*/
|
|
2409
|
-
_extractMDocuments(documents, metadata, { prepareMGet = false, requireId = false, prepareMUpsert = false } = {}) {
|
|
2410
|
-
const rejected = [];
|
|
2411
|
-
const extractedDocuments = [];
|
|
2412
|
-
const documentsToGet = [];
|
|
2413
|
-
/**
|
|
2414
|
-
* @warning Critical code section
|
|
2415
|
-
*
|
|
2416
|
-
* request can contain more than 10K elements
|
|
2417
|
-
*/
|
|
2418
|
-
for (const document of documents) {
|
|
2419
|
-
if (!(0, safeObject_1.isPlainObject)(document.body) && !prepareMUpsert) {
|
|
2420
|
-
rejected.push({
|
|
2421
|
-
document,
|
|
2422
|
-
reason: "document body must be an object",
|
|
2423
|
-
status: 400,
|
|
2424
|
-
});
|
|
2425
|
-
}
|
|
2426
|
-
else if (!(0, safeObject_1.isPlainObject)(document.changes) && prepareMUpsert) {
|
|
2427
|
-
rejected.push({
|
|
2428
|
-
document,
|
|
2429
|
-
reason: "document changes must be an object",
|
|
2430
|
-
status: 400,
|
|
2431
|
-
});
|
|
2432
|
-
}
|
|
2433
|
-
else if (prepareMUpsert &&
|
|
2434
|
-
document.default &&
|
|
2435
|
-
!(0, safeObject_1.isPlainObject)(document.default)) {
|
|
2436
|
-
rejected.push({
|
|
2437
|
-
document,
|
|
2438
|
-
reason: "document default must be an object",
|
|
2439
|
-
status: 400,
|
|
2440
|
-
});
|
|
2441
|
-
}
|
|
2442
|
-
else if (requireId && typeof document._id !== "string") {
|
|
2443
|
-
rejected.push({
|
|
2444
|
-
document,
|
|
2445
|
-
reason: "document _id must be a string",
|
|
2446
|
-
status: 400,
|
|
2447
|
-
});
|
|
2448
|
-
}
|
|
2449
|
-
else {
|
|
2450
|
-
this._processExtract(prepareMUpsert, prepareMGet, metadata, document, extractedDocuments, documentsToGet);
|
|
2451
|
-
}
|
|
2452
|
-
}
|
|
2453
|
-
/* end critical code section */
|
|
2454
|
-
return { documentsToGet, extractedDocuments, rejected };
|
|
2455
|
-
}
|
|
2456
|
-
_hasExceededLimit(limits, documents) {
|
|
2457
|
-
return (limits &&
|
|
2458
|
-
documents.length > global.kuzzle.config.limits.documentsWriteCount);
|
|
2459
|
-
}
|
|
2460
|
-
_processExtract(prepareMUpsert, prepareMGet, metadata, document, extractedDocuments, documentsToGet) {
|
|
2461
|
-
let extractedDocument;
|
|
2462
|
-
if (prepareMUpsert) {
|
|
2463
|
-
if (document.changes !== undefined && document.changes !== null) {
|
|
2464
|
-
delete document.changes._kuzzle_info;
|
|
2465
|
-
}
|
|
2466
|
-
extractedDocument = {
|
|
2467
|
-
_source: {
|
|
2468
|
-
// Do not use destructuring, it's 10x slower
|
|
2469
|
-
changes: Object.assign({}, metadata.doc, document.changes),
|
|
2470
|
-
default: Object.assign({}, metadata.upsert, document.changes, document.default),
|
|
2471
|
-
},
|
|
2472
|
-
};
|
|
2473
|
-
}
|
|
2474
|
-
else {
|
|
2475
|
-
extractedDocument = {
|
|
2476
|
-
// Do not use destructuring, it's 10x slower
|
|
2477
|
-
_source: Object.assign({}, metadata, document.body),
|
|
2478
|
-
};
|
|
2479
|
-
}
|
|
2480
|
-
if (document._id) {
|
|
2481
|
-
extractedDocument._id = document._id;
|
|
2482
|
-
}
|
|
2483
|
-
extractedDocuments.push(extractedDocument);
|
|
2484
|
-
if (prepareMGet && typeof document._id === "string") {
|
|
2485
|
-
documentsToGet.push({
|
|
2486
|
-
_id: document._id,
|
|
2487
|
-
_source: false,
|
|
2488
|
-
});
|
|
2489
|
-
}
|
|
2490
|
-
}
|
|
2491
|
-
/**
|
|
2492
|
-
* Throws an error if the provided mapping is invalid
|
|
2493
|
-
*
|
|
2494
|
-
* @param {Object} mapping
|
|
2495
|
-
* @throws
|
|
2496
|
-
*/
|
|
2497
|
-
_checkMappings(mapping, path = [], check = true) {
|
|
2498
|
-
const properties = Object.keys(mapping);
|
|
2499
|
-
const mappingProperties = path.length === 0
|
|
2500
|
-
? ROOT_MAPPING_PROPERTIES
|
|
2501
|
-
: [...ROOT_MAPPING_PROPERTIES, ...CHILD_MAPPING_PROPERTIES];
|
|
2502
|
-
for (const property of properties) {
|
|
2503
|
-
if (check && !mappingProperties.includes(property)) {
|
|
2504
|
-
const currentPath = [...path, property].join(".");
|
|
2505
|
-
throw kerror.get("services", "storage", "invalid_mapping", currentPath, (0, didYouMean_1.default)(property, mappingProperties));
|
|
2506
|
-
}
|
|
2507
|
-
if (property === "properties") {
|
|
2508
|
-
// type definition level, we don't check
|
|
2509
|
-
this._checkMappings(mapping[property], [...path, "properties"], false);
|
|
2510
|
-
}
|
|
2511
|
-
else if (mapping[property]?.properties) {
|
|
2512
|
-
// root properties level, check for "properties", "dynamic" and "_meta"
|
|
2513
|
-
this._checkMappings(mapping[property], [...path, property], true);
|
|
2514
|
-
}
|
|
2515
|
-
}
|
|
2516
|
-
}
|
|
2517
|
-
/**
|
|
2518
|
-
* Given index + collection, returns the associated alias name.
|
|
2519
|
-
* Prefer this function to `_getIndice` and `_getAvailableIndice` whenever it is possible.
|
|
2520
|
-
*
|
|
2521
|
-
* @param {String} index
|
|
2522
|
-
* @param {String} collection
|
|
2523
|
-
*
|
|
2524
|
-
* @returns {String} Alias name (eg: '@&nepali.liia')
|
|
2525
|
-
*/
|
|
2526
|
-
_getAlias(index, collection) {
|
|
2527
|
-
return `${ALIAS_PREFIX}${this._indexPrefix}${index}${NAME_SEPARATOR}${collection}`;
|
|
2528
|
-
}
|
|
2529
|
-
/**
|
|
2530
|
-
* Given an alias name, returns the associated index name.
|
|
2531
|
-
*/
|
|
2532
|
-
async _checkIfAliasExists(aliasName) {
|
|
2533
|
-
return this._client.indices.existsAlias({
|
|
2534
|
-
name: aliasName,
|
|
2535
|
-
});
|
|
2536
|
-
}
|
|
2537
|
-
/**
|
|
2538
|
-
* Given index + collection, returns the associated indice name.
|
|
2539
|
-
* Use this function if ES does not accept aliases in the request. Otherwise use `_getAlias`.
|
|
2540
|
-
*
|
|
2541
|
-
* @param {String} index
|
|
2542
|
-
* @param {String} collection
|
|
2543
|
-
*
|
|
2544
|
-
* @returns {String} Indice name (eg: '&nepali.liia')
|
|
2545
|
-
* @throws If there is not exactly one indice associated
|
|
2546
|
-
*/
|
|
2547
|
-
async _getIndice(index, collection) {
|
|
2548
|
-
const alias = `${ALIAS_PREFIX}${this._indexPrefix}${index}${NAME_SEPARATOR}${collection}`;
|
|
2549
|
-
const body = await this._catAliases(alias);
|
|
2550
|
-
const [record] = body;
|
|
2551
|
-
if (record === undefined) {
|
|
2552
|
-
throw kerror.get("services", "storage", "unknown_index_collection");
|
|
2553
|
-
}
|
|
2554
|
-
else if (body.length > 1) {
|
|
2555
|
-
throw kerror.get("services", "storage", "multiple_indice_alias", `"alias" starting with "${ALIAS_PREFIX}"`, '"indices"');
|
|
2556
|
-
}
|
|
2557
|
-
return record.index;
|
|
2558
|
-
}
|
|
2559
|
-
/**
|
|
2560
|
-
* Given an ES Request returns the settings of the corresponding indice.
|
|
2561
|
-
*
|
|
2562
|
-
* @param esRequest the ES Request with wanted settings.
|
|
2563
|
-
* @return {Promise<*>} the settings of the indice.
|
|
2564
|
-
* @private
|
|
2565
|
-
*/
|
|
2566
|
-
async _getSettings(esRequest) {
|
|
2567
|
-
const response = await this._client.indices.getSettings(esRequest);
|
|
2568
|
-
const index = esRequest.index;
|
|
2569
|
-
return response[index]?.settings;
|
|
2570
|
-
}
|
|
2571
|
-
/**
|
|
2572
|
-
* Given index + collection, returns an available indice name.
|
|
2573
|
-
* Use this function when creating the associated indice. Otherwise use `_getAlias`.
|
|
2574
|
-
*
|
|
2575
|
-
* @param {String} index
|
|
2576
|
-
* @param {String} collection
|
|
2577
|
-
*
|
|
2578
|
-
* @returns {String} Available indice name (eg: '&nepali.liia2')
|
|
2579
|
-
*/
|
|
2580
|
-
async _getAvailableIndice(index, collection) {
|
|
2581
|
-
let indice = this._getAlias(index, collection).substring(INDEX_PREFIX_POSITION_IN_ALIAS);
|
|
2582
|
-
if (!(await this._client.indices.exists({ index: indice }))) {
|
|
2583
|
-
return indice;
|
|
2584
|
-
}
|
|
2585
|
-
let notAvailable;
|
|
2586
|
-
let suffix;
|
|
2587
|
-
do {
|
|
2588
|
-
suffix = `.${this._getRandomNumber(100000)}`;
|
|
2589
|
-
const overflow = Buffer.from(indice + suffix).length - 255;
|
|
2590
|
-
if (overflow > 0) {
|
|
2591
|
-
const indiceBuffer = Buffer.from(indice);
|
|
2592
|
-
indice = indiceBuffer
|
|
2593
|
-
.subarray(0, indiceBuffer.length - overflow)
|
|
2594
|
-
.toString();
|
|
2595
|
-
}
|
|
2596
|
-
notAvailable = await this._client.indices.exists({
|
|
2597
|
-
index: indice + suffix,
|
|
2598
|
-
});
|
|
2599
|
-
} while (notAvailable);
|
|
2600
|
-
return indice + suffix;
|
|
2601
|
-
}
|
|
2602
|
-
/**
|
|
2603
|
-
* Given an indice, returns the associated alias name.
|
|
2604
|
-
*
|
|
2605
|
-
* @param {String} indice
|
|
2606
|
-
*
|
|
2607
|
-
* @returns {String} Alias name (eg: '@&nepali.liia')
|
|
2608
|
-
* @throws If there is not exactly one alias associated that is prefixed with @
|
|
2609
|
-
*/
|
|
2610
|
-
async _getAliasFromIndice(indice) {
|
|
2611
|
-
const body = await this._client.indices.getAlias({ index: indice });
|
|
2612
|
-
const indiceAliases = body[indice]?.aliases ?? {};
|
|
2613
|
-
const [first, ...others] = Object.keys(indiceAliases).filter((alias) => alias.startsWith(ALIAS_PREFIX));
|
|
2614
|
-
// The non-empty tuple is what lets every caller read aliases[0] without a
|
|
2615
|
-
// guard the throw below already made redundant.
|
|
2616
|
-
if (first === undefined) {
|
|
2617
|
-
throw kerror.get("services", "storage", "unknown_index_collection");
|
|
2618
|
-
}
|
|
2619
|
-
return [first, ...others];
|
|
2620
|
-
}
|
|
2621
|
-
/**
|
|
2622
|
-
* `cat.aliases` declares `alias` and `index` as optional. Defaulting them
|
|
2623
|
-
* once here is what lets every caller index into an alias without repeating
|
|
2624
|
-
* the check — and an empty alias fails the index-prefix test every caller
|
|
2625
|
-
* applies, which is what a row without one used to throw on.
|
|
2626
|
-
*/
|
|
2627
|
-
async _catAliases(name) {
|
|
2628
|
-
const body = await this._client.cat.aliases(name === undefined ? { format: "json" } : { format: "json", name });
|
|
2629
|
-
return body.map(({ alias, index }) => ({
|
|
2630
|
-
alias: alias ?? "",
|
|
2631
|
-
index: index ?? "",
|
|
2632
|
-
}));
|
|
2633
|
-
}
|
|
2634
|
-
/**
|
|
2635
|
-
* Returns the indices marked with `UNMANAGED_INDICE_ALIAS`.
|
|
2636
|
-
*/
|
|
2637
|
-
async _listUnmanagedIndices() {
|
|
2638
|
-
const body = await this._catAliases();
|
|
2639
|
-
return new Set(body
|
|
2640
|
-
.filter(({ alias }) => alias === UNMANAGED_INDICE_ALIAS)
|
|
2641
|
-
.map(({ index }) => index));
|
|
2642
|
-
}
|
|
2643
|
-
/**
|
|
2644
|
-
* Check for each indice whether it has an alias or not.
|
|
2645
|
-
* When the latter is missing, create one based on the indice name.
|
|
2646
|
-
*
|
|
2647
|
-
* This check avoids a breaking change for those who were using Kuzzle before
|
|
2648
|
-
* alias attribution for each indice turned into a standard (appear in 2.14.0).
|
|
2649
|
-
*/
|
|
2650
|
-
async generateMissingAliases() {
|
|
2651
|
-
try {
|
|
2652
|
-
const body = await this._client.cat.indices({ format: "json" });
|
|
2653
|
-
const indices = body.flatMap(({ index: indice }) => indice === undefined ? [] : [indice]);
|
|
2654
|
-
const aliases = await this.listAliases();
|
|
2655
|
-
const unmanaged = await this._listUnmanagedIndices();
|
|
2656
|
-
const indicesWithoutAlias = indices.filter((indice) => indice[INDEX_PREFIX_POSITION_IN_INDICE] === this._indexPrefix &&
|
|
2657
|
-
!unmanaged.has(indice) &&
|
|
2658
|
-
!aliases.some((alias) => alias.indice === indice));
|
|
2659
|
-
const esRequest = {
|
|
2660
|
-
body: { actions: [] },
|
|
2661
|
-
};
|
|
2662
|
-
for (const indice of indicesWithoutAlias) {
|
|
2663
|
-
esRequest.body.actions.push({
|
|
2664
|
-
add: { alias: `${ALIAS_PREFIX}${indice}`, index: indice },
|
|
2665
|
-
});
|
|
2666
|
-
}
|
|
2667
|
-
if (esRequest.body.actions.length > 0) {
|
|
2668
|
-
await this._client.indices.updateAliases(esRequest);
|
|
2669
|
-
}
|
|
2670
|
-
}
|
|
2671
|
-
catch (error) {
|
|
2672
|
-
throw this._esWrapper.formatESError(error);
|
|
2673
|
-
}
|
|
2674
|
-
}
|
|
2675
|
-
/**
|
|
2676
|
-
* Throws if index or collection includes forbidden characters
|
|
2677
|
-
*
|
|
2678
|
-
* @param {String} index
|
|
2679
|
-
* @param {String} collection
|
|
2680
|
-
*/
|
|
2681
|
-
_assertValidIndexAndCollection(index, collection = null) {
|
|
2682
|
-
if (!this.isIndexNameValid(index)) {
|
|
2683
|
-
throw kerror.get("services", "storage", "invalid_index_name", index);
|
|
2684
|
-
}
|
|
2685
|
-
if (collection !== null && !this.isCollectionNameValid(collection)) {
|
|
2686
|
-
throw kerror.get("services", "storage", "invalid_collection_name", collection);
|
|
2687
|
-
}
|
|
2688
|
-
}
|
|
2689
|
-
/**
|
|
2690
|
-
* Given an alias, extract the associated index.
|
|
2691
|
-
*
|
|
2692
|
-
* @param {String} alias
|
|
2693
|
-
*
|
|
2694
|
-
* @returns {String} Index name
|
|
2695
|
-
*/
|
|
2696
|
-
_extractIndex(alias) {
|
|
2697
|
-
return alias.substr(INDEX_PREFIX_POSITION_IN_ALIAS + 1, alias.indexOf(NAME_SEPARATOR) - INDEX_PREFIX_POSITION_IN_ALIAS - 1);
|
|
2698
|
-
}
|
|
2699
|
-
/**
|
|
2700
|
-
* Given an alias, extract the associated collection.
|
|
2701
|
-
*
|
|
2702
|
-
* @param {String} alias
|
|
2703
|
-
*
|
|
2704
|
-
* @returns {String} Collection name
|
|
2705
|
-
*/
|
|
2706
|
-
_extractCollection(alias) {
|
|
2707
|
-
const separatorPos = alias.indexOf(NAME_SEPARATOR);
|
|
2708
|
-
return alias.substr(separatorPos + 1, alias.length);
|
|
2709
|
-
}
|
|
2710
|
-
/**
|
|
2711
|
-
* Given aliases, extract indexes and collections.
|
|
2712
|
-
*
|
|
2713
|
-
* @param {Array.<String>} aliases
|
|
2714
|
-
* @param {Object.Boolean} includeHidden Only refers to `HIDDEN_COLLECTION` occurences. An empty index will still be listed. Default to `false`.
|
|
2715
|
-
*
|
|
2716
|
-
* @returns {Object.<String, String[]>} Indexes as key and an array of their collections as value
|
|
2717
|
-
*/
|
|
2718
|
-
_extractSchema(aliases, { includeHidden = false } = {}) {
|
|
2719
|
-
const schema = {};
|
|
2720
|
-
for (const alias of aliases) {
|
|
2721
|
-
// `split` always yields a first element; the defaults are what make that
|
|
2722
|
-
// readable to the compiler.
|
|
2723
|
-
const [indexName = "", collectionName = ""] = alias
|
|
2724
|
-
.slice(INDEX_PREFIX_POSITION_IN_ALIAS + 1)
|
|
2725
|
-
.split(NAME_SEPARATOR);
|
|
2726
|
-
if (alias[INDEX_PREFIX_POSITION_IN_ALIAS] === this._indexPrefix &&
|
|
2727
|
-
(collectionName !== HIDDEN_COLLECTION || includeHidden)) {
|
|
2728
|
-
const collections = (schema[indexName] ?? (schema[indexName] = []));
|
|
2729
|
-
if (!collections.includes(collectionName)) {
|
|
2730
|
-
collections.push(collectionName);
|
|
2731
|
-
}
|
|
2732
|
-
}
|
|
2733
|
-
}
|
|
2734
|
-
return schema;
|
|
2735
|
-
}
|
|
2736
|
-
/**
|
|
2737
|
-
* Creates the hidden collection on the provided index if it does not already
|
|
2738
|
-
* exists
|
|
2739
|
-
*
|
|
2740
|
-
* @param {String} index Index name
|
|
2741
|
-
*/
|
|
2742
|
-
async _createHiddenCollection(index) {
|
|
2743
|
-
try {
|
|
2744
|
-
await (0, distributedLock_1.withLock)(`hiddenCollection/${index}`, async () => {
|
|
2745
|
-
if (await this._hasHiddenCollection(index)) {
|
|
2746
|
-
return;
|
|
2747
|
-
}
|
|
2748
|
-
const esRequest = {
|
|
2749
|
-
aliases: {
|
|
2750
|
-
[this._getAlias(index, HIDDEN_COLLECTION)]: {},
|
|
2751
|
-
},
|
|
2752
|
-
index: await this._getAvailableIndice(index, HIDDEN_COLLECTION),
|
|
2753
|
-
settings: {
|
|
2754
|
-
number_of_replicas: this._config.defaultSettings.number_of_replicas,
|
|
2755
|
-
number_of_shards: this._config.defaultSettings.number_of_shards,
|
|
2756
|
-
},
|
|
2757
|
-
wait_for_active_shards: await this._getWaitForActiveShards(),
|
|
2758
|
-
};
|
|
2759
|
-
await this._client.indices.create(esRequest);
|
|
2760
|
-
}, HIDDEN_COLLECTION_LOCK);
|
|
2761
|
-
}
|
|
2762
|
-
catch (e) {
|
|
2763
|
-
throw this._esWrapper.formatESError(e);
|
|
2764
|
-
}
|
|
2765
|
-
}
|
|
2766
|
-
/**
|
|
2767
|
-
* We need to always wait for a minimal number of shards to be available
|
|
2768
|
-
* before answering to the client. This is to avoid Elasticsearch node
|
|
2769
|
-
* to return a 404 Not Found error when the client tries to index a
|
|
2770
|
-
* document in the index.
|
|
2771
|
-
* To find the best value for this setting, we need to take into account
|
|
2772
|
-
* the number of nodes in the cluster and the number of shards per index.
|
|
2773
|
-
*/
|
|
2774
|
-
async _getWaitForActiveShards() {
|
|
2775
|
-
const body = await this._client.cat.nodes({ format: "json" });
|
|
2776
|
-
const numberOfNodes = body.length;
|
|
2777
|
-
if (numberOfNodes > 1) {
|
|
2778
|
-
return "all";
|
|
2779
|
-
}
|
|
2780
|
-
return 1;
|
|
2781
|
-
}
|
|
2782
|
-
/**
|
|
2783
|
-
* Scroll indice in elasticsearch and return all document that match the filter
|
|
2784
|
-
* /!\ throws a write_limit_exceed error: this method is intended to be used
|
|
2785
|
-
* by deleteByQuery and updateByQuery
|
|
2786
|
-
*
|
|
2787
|
-
* @param {Object} esRequest - Search request body
|
|
2788
|
-
*
|
|
2789
|
-
* @returns {Promise.<Array>} resolve to an array of documents
|
|
2790
|
-
*/
|
|
2791
|
-
async _getAllDocumentsFromQuery(esRequest) {
|
|
2792
|
-
let { hits, _scroll_id } = await this._client.search(esRequest);
|
|
2793
|
-
const totalHitsValue = this._getHitsTotalValue(hits);
|
|
2794
|
-
if (totalHitsValue > global.kuzzle.config.limits.documentsWriteCount) {
|
|
2795
|
-
throw kerror.get("services", "storage", "write_limit_exceeded");
|
|
2796
|
-
}
|
|
2797
|
-
let documents = hits.hits.map((h) => ({
|
|
2798
|
-
_id: h._id,
|
|
2799
|
-
_source: h._source,
|
|
2800
|
-
body: {},
|
|
2801
|
-
}));
|
|
2802
|
-
while (totalHitsValue !== documents.length) {
|
|
2803
|
-
({ hits, _scroll_id } = await this._client.scroll({
|
|
2804
|
-
scroll: esRequest.scroll,
|
|
2805
|
-
scroll_id: _scroll_id,
|
|
2806
|
-
}));
|
|
2807
|
-
documents = documents.concat(hits.hits.map((h) => ({
|
|
2808
|
-
_id: h._id,
|
|
2809
|
-
_source: h._source,
|
|
2810
|
-
body: {},
|
|
2811
|
-
})));
|
|
2812
|
-
}
|
|
2813
|
-
await this.clearScroll(_scroll_id);
|
|
2814
|
-
return documents;
|
|
2815
|
-
}
|
|
2816
|
-
/**
|
|
2817
|
-
* Clean and normalize the searchBody
|
|
2818
|
-
* Ensure only allowed parameters are passed to ES
|
|
2819
|
-
*
|
|
2820
|
-
* @param {Object} searchBody - ES search body (with query, aggregations, sort, etc)
|
|
2821
|
-
*/
|
|
2822
|
-
_sanitizeSearchBody(searchBody = {}) {
|
|
2823
|
-
// Only allow a whitelist of top level properties
|
|
2824
|
-
for (const key of Object.keys(searchBody)) {
|
|
2825
|
-
if (searchBody[key] !== undefined && !this.searchBodyKeys.includes(key)) {
|
|
2826
|
-
throw kerror.get("services", "storage", "invalid_search_query", key);
|
|
2827
|
-
}
|
|
2828
|
-
}
|
|
2829
|
-
// Ensure that the body does not include a script
|
|
2830
|
-
this._scriptCheck(searchBody);
|
|
2831
|
-
// Avoid empty queries that causes ES to respond with an error.
|
|
2832
|
-
// Empty queries are turned into match_all queries
|
|
2833
|
-
if (lodash_1.default.isEmpty(searchBody.query)) {
|
|
2834
|
-
searchBody.query = { match_all: {} };
|
|
2835
|
-
}
|
|
2836
|
-
return searchBody;
|
|
2837
|
-
}
|
|
2838
|
-
/**
|
|
2839
|
-
* Throw if a script is used in the query.
|
|
2840
|
-
*
|
|
2841
|
-
* Only Stored Scripts are accepted
|
|
2842
|
-
*
|
|
2843
|
-
* @param {Object} object
|
|
2844
|
-
*/
|
|
2845
|
-
_scriptCheck(object) {
|
|
2846
|
-
for (const [key, value] of Object.entries(object)) {
|
|
2847
|
-
if (this.scriptKeys.includes(key)) {
|
|
2848
|
-
for (const scriptArg of Object.keys(value)) {
|
|
2849
|
-
if (!this.scriptAllowedArgs.includes(scriptArg)) {
|
|
2850
|
-
throw kerror.get("services", "storage", "invalid_query_keyword", `${key}.${scriptArg}`);
|
|
2851
|
-
}
|
|
2852
|
-
}
|
|
2853
|
-
}
|
|
2854
|
-
// Every object must be checked here, even the ones nested into an array
|
|
2855
|
-
else if (typeof value === "object" && value !== null) {
|
|
2856
|
-
this._scriptCheck(value);
|
|
2857
|
-
}
|
|
2858
|
-
}
|
|
2859
|
-
}
|
|
2860
|
-
/**
|
|
2861
|
-
* Checks if a collection name is valid
|
|
2862
|
-
* @param {string} name
|
|
2863
|
-
* @returns {Boolean}
|
|
2864
|
-
*/
|
|
2865
|
-
isCollectionNameValid(name) {
|
|
2866
|
-
return _isObjectNameValid(name);
|
|
2867
|
-
}
|
|
2868
|
-
/**
|
|
2869
|
-
* Checks if a collection name is valid
|
|
2870
|
-
* @param {string} name
|
|
2871
|
-
* @returns {Boolean}
|
|
2872
|
-
*/
|
|
2873
|
-
isIndexNameValid(name) {
|
|
2874
|
-
return _isObjectNameValid(name);
|
|
2875
|
-
}
|
|
2876
|
-
/**
|
|
2877
|
-
* Clears an allocated scroll
|
|
2878
|
-
* @param {[type]} id [description]
|
|
2879
|
-
* @returns {[type]} [description]
|
|
2880
|
-
*/
|
|
2881
|
-
async clearScroll(id) {
|
|
2882
|
-
if (id) {
|
|
2883
|
-
this.logger.debug("clearing scroll: %s", id);
|
|
2884
|
-
await this._client.clearScroll({ scroll_id: id });
|
|
2885
|
-
}
|
|
2886
|
-
}
|
|
2887
|
-
/**
|
|
2888
|
-
* Loads a configuration value from services.storageEngine and assert a valid
|
|
2889
|
-
* ms format.
|
|
2890
|
-
*
|
|
2891
|
-
* @param {String} key - relative path to the key in configuration
|
|
2892
|
-
*
|
|
2893
|
-
* @returns {Number} milliseconds
|
|
2894
|
-
*/
|
|
2895
|
-
_loadMsConfig(key) {
|
|
2896
|
-
const configValue = lodash_1.default.get(this._config, key);
|
|
2897
|
-
(0, assert_1.default)(typeof configValue === "string", `services.storageEngine.${key} must be a string.`);
|
|
2898
|
-
const parsedValue = (0, ms_1.default)(configValue);
|
|
2899
|
-
(0, assert_1.default)(typeof parsedValue === "number", `Invalid parsed value from ms() for services.storageEngine.${key} ("${typeof parsedValue}").`);
|
|
2900
|
-
return parsedValue;
|
|
2901
|
-
}
|
|
2902
|
-
/**
|
|
2903
|
-
* Returns true if one of the mappings dynamic property changes value from
|
|
2904
|
-
* false to true
|
|
2905
|
-
*/
|
|
2906
|
-
_dynamicChanges(previousMappings, newMappings) {
|
|
2907
|
-
const previousValues = findDynamic(previousMappings);
|
|
2908
|
-
for (const [path, previousValue] of Object.entries(previousValues)) {
|
|
2909
|
-
if (previousValue.toString() !== "false") {
|
|
2910
|
-
continue;
|
|
2911
|
-
}
|
|
2912
|
-
const newValue = lodash_1.default.get(newMappings, path);
|
|
2913
|
-
if (newValue && newValue.toString() !== "false") {
|
|
2914
|
-
return true;
|
|
2915
|
-
}
|
|
2916
|
-
}
|
|
2917
|
-
return false;
|
|
2918
|
-
}
|
|
2919
|
-
async waitForElasticsearch() {
|
|
2920
|
-
if (esState !== esStateEnum.NONE) {
|
|
2921
|
-
while (esState !== esStateEnum.OK) {
|
|
2922
|
-
await bluebird_1.default.delay(1000);
|
|
2923
|
-
}
|
|
2924
|
-
return;
|
|
2925
|
-
}
|
|
2926
|
-
esState = esStateEnum.AWAITING;
|
|
2927
|
-
this.logger.info("[ℹ] Trying to connect to Elasticsearch...");
|
|
2928
|
-
while (esState !== esStateEnum.OK) {
|
|
2929
|
-
try {
|
|
2930
|
-
// Wait for at least 1 shard to be initialized
|
|
2931
|
-
const health = await this._client.cluster.health({
|
|
2932
|
-
wait_for_no_initializing_shards: true,
|
|
2933
|
-
});
|
|
2934
|
-
if (health.number_of_pending_tasks === 0) {
|
|
2935
|
-
this.logger.info("[✔] Elasticsearch is ready");
|
|
2936
|
-
esState = esStateEnum.OK;
|
|
2937
|
-
}
|
|
2938
|
-
else {
|
|
2939
|
-
this.logger.info(`[ℹ] Still waiting for Elasticsearch: ${health.number_of_pending_tasks} cluster tasks remaining`);
|
|
2940
|
-
await bluebird_1.default.delay(1000);
|
|
2941
|
-
}
|
|
2942
|
-
}
|
|
2943
|
-
catch {
|
|
2944
|
-
await bluebird_1.default.delay(1000);
|
|
2945
|
-
}
|
|
2946
|
-
}
|
|
2947
|
-
}
|
|
2948
|
-
/**
|
|
2949
|
-
* Checks if the dynamic properties are correct
|
|
2950
|
-
*/
|
|
2951
|
-
_checkDynamicProperty(mappings) {
|
|
2952
|
-
const dynamicProperties = findDynamic(mappings);
|
|
2953
|
-
for (const [path, value] of Object.entries(dynamicProperties)) {
|
|
2954
|
-
// Prevent common mistake
|
|
2955
|
-
if (typeof value === "boolean") {
|
|
2956
|
-
lodash_1.default.set(mappings, path, value.toString());
|
|
2957
|
-
}
|
|
2958
|
-
else if (typeof value !== "string") {
|
|
2959
|
-
throw kerror.get("services", "storage", "invalid_mapping", path, "Dynamic property value should be a string.");
|
|
2960
|
-
}
|
|
2961
|
-
if (!DYNAMIC_PROPERTY_VALUES.includes(value.toString())) {
|
|
2962
|
-
throw kerror.get("services", "storage", "invalid_mapping", path, `Incorrect dynamic property value (${value}). Should be one of "${DYNAMIC_PROPERTY_VALUES.join('", "')}"`);
|
|
2963
|
-
}
|
|
2964
|
-
}
|
|
2965
|
-
}
|
|
2966
|
-
_setLastActionToKuzzleMeta(esRequest, alias, kuzzleMeta) {
|
|
2967
|
-
/**
|
|
2968
|
-
* @warning Critical code section
|
|
2969
|
-
*
|
|
2970
|
-
* bulk body can contain more than 10K elements
|
|
2971
|
-
*/
|
|
2972
|
-
let lastAction = "";
|
|
2973
|
-
const actionNames = ["index", "create", "update", "delete"];
|
|
2974
|
-
for (let i = 0; i < esRequest.operations.length; i++) {
|
|
2975
|
-
const item = esRequest.operations[i];
|
|
2976
|
-
const action = Object.keys(item)[0] ?? "";
|
|
2977
|
-
if (actionNames.indexOf(action) !== -1) {
|
|
2978
|
-
lastAction = action;
|
|
2979
|
-
item[action]._index = alias;
|
|
2980
|
-
if (item[action]?._type) {
|
|
2981
|
-
item[action]._type = undefined;
|
|
2982
|
-
}
|
|
2983
|
-
}
|
|
2984
|
-
else if (lastAction === "index" || lastAction === "create") {
|
|
2985
|
-
item._kuzzle_info = kuzzleMeta.created;
|
|
2986
|
-
}
|
|
2987
|
-
else if (lastAction === "update") {
|
|
2988
|
-
this._setLastActionToKuzzleMetaUpdate(item, kuzzleMeta);
|
|
2989
|
-
}
|
|
2990
|
-
}
|
|
2991
|
-
/* end critical code section */
|
|
2992
|
-
}
|
|
2993
|
-
_setLastActionToKuzzleMetaUpdate(item, kuzzleMeta) {
|
|
2994
|
-
for (const prop of ["doc", "upsert"]) {
|
|
2995
|
-
if ((0, safeObject_1.isPlainObject)(item[prop])) {
|
|
2996
|
-
item[prop]._kuzzle_info = kuzzleMeta.updated;
|
|
2997
|
-
}
|
|
2998
|
-
}
|
|
2999
|
-
}
|
|
3000
|
-
_getHitsTotalValue(hits) {
|
|
3001
|
-
if (typeof hits.total === "number") {
|
|
3002
|
-
return hits.total;
|
|
3003
|
-
}
|
|
3004
|
-
return hits.total?.value ?? 0;
|
|
3005
|
-
}
|
|
3006
|
-
_getRandomNumber(number) {
|
|
3007
|
-
return (0, name_generator_1.randomNumber)(number);
|
|
3008
|
-
}
|
|
3009
|
-
}
|
|
3010
|
-
exports.ES8 = ES8;
|
|
3011
|
-
/**
|
|
3012
|
-
* Finds paths and values of mappings dynamic properties
|
|
3013
|
-
*
|
|
3014
|
-
* @example
|
|
3015
|
-
*
|
|
3016
|
-
* findDynamic(mappings);
|
|
3017
|
-
* {
|
|
3018
|
-
* "properties.metadata.dynamic": "true",
|
|
3019
|
-
* "properties.user.properties.address.dynamic": "strict"
|
|
3020
|
-
* }
|
|
3021
|
-
*/
|
|
3022
|
-
function findDynamic(mappings, path = [], results = {}) {
|
|
3023
|
-
if (mappings.dynamic !== undefined) {
|
|
3024
|
-
results[path.concat("dynamic").join(".")] = mappings.dynamic;
|
|
3025
|
-
}
|
|
3026
|
-
for (const [key, value] of Object.entries(mappings)) {
|
|
3027
|
-
if ((0, safeObject_1.isPlainObject)(value)) {
|
|
3028
|
-
findDynamic(value, path.concat(key), results);
|
|
3029
|
-
}
|
|
3030
|
-
}
|
|
3031
|
-
return results;
|
|
3032
|
-
}
|
|
3033
|
-
/**
|
|
3034
|
-
* Forbids the use of the _routing ES option
|
|
3035
|
-
*
|
|
3036
|
-
* @param {Object} esRequest
|
|
3037
|
-
* @throws
|
|
3038
|
-
*/
|
|
3039
|
-
function assertNoRouting(esRequest) {
|
|
3040
|
-
if (esRequest._routing) {
|
|
3041
|
-
throw kerror.get("services", "storage", "no_routing");
|
|
3042
|
-
}
|
|
3043
|
-
}
|
|
3044
|
-
/**
|
|
3045
|
-
* Checks if the optional "refresh" argument is well-formed
|
|
3046
|
-
*
|
|
3047
|
-
* @param {Object} esRequest
|
|
3048
|
-
* @throws
|
|
3049
|
-
*/
|
|
3050
|
-
function assertWellFormedRefresh(esRequest) {
|
|
3051
|
-
if (!["wait_for", "false", false, undefined].includes(esRequest.refresh)) {
|
|
3052
|
-
throw kerror.get("services", "storage", "invalid_argument", "refresh", '"wait_for", false');
|
|
3053
|
-
}
|
|
3054
|
-
}
|
|
3055
|
-
function getKuid(userId) {
|
|
3056
|
-
if (!userId) {
|
|
3057
|
-
return null;
|
|
3058
|
-
}
|
|
3059
|
-
return String(userId);
|
|
3060
|
-
}
|
|
3061
|
-
/**
|
|
3062
|
-
* Checks if an index or collection name is valid
|
|
3063
|
-
*
|
|
3064
|
-
* @see https://www.elastic.co/guide/en/elasticsearch/reference/7.4/indices-create-index.html
|
|
3065
|
-
*
|
|
3066
|
-
* Beware of the length check: ES allows indice names up to 255 bytes, but since
|
|
3067
|
-
* in Kuzzle we emulate collections as indices, we have to make sure
|
|
3068
|
-
* that the privacy prefix, the index name, the separator and the collection
|
|
3069
|
-
* name ALL fit within the 255-bytes limit of Elasticsearch. The simplest way
|
|
3070
|
-
* is to limit index and collection names to 126 bytes and document that
|
|
3071
|
-
* limitation (prefix(1) + index(1..126) + sep(1) + collection(1..126) = 4..254)
|
|
3072
|
-
*
|
|
3073
|
-
* @param {string} name
|
|
3074
|
-
* @returns {Boolean}
|
|
3075
|
-
*/
|
|
3076
|
-
function _isObjectNameValid(name) {
|
|
3077
|
-
if (typeof name !== "string" || name.length === 0) {
|
|
3078
|
-
return false;
|
|
3079
|
-
}
|
|
3080
|
-
if (name.toLowerCase() !== name) {
|
|
3081
|
-
return false;
|
|
3082
|
-
}
|
|
3083
|
-
if (Buffer.from(name).length > 126) {
|
|
3084
|
-
return false;
|
|
3085
|
-
}
|
|
3086
|
-
if (name === "_all") {
|
|
3087
|
-
return false;
|
|
3088
|
-
}
|
|
3089
|
-
for (const forbiddenChar of FORBIDDEN_CHARS) {
|
|
3090
|
-
if (name.includes(forbiddenChar)) {
|
|
3091
|
-
return false;
|
|
3092
|
-
}
|
|
3093
|
-
}
|
|
3094
|
-
return true;
|
|
3095
|
-
}
|
|
3096
|
-
//# sourceMappingURL=elasticsearch.js.map
|