-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathElasticsearchIndex.js
440 lines (422 loc) · 13.1 KB
/
ElasticsearchIndex.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
require('rubico/global')
const Http = require('./Http')
const x = require('rubico/x')
const querystring = require('querystring')
const { noop } = x
/**
* @name ElasticsearchIndex
*
* @synopsis
* ```coffeescript [specscript]
* new ElasticsearchIndex(options {
* node: string, // 'http://localhost:9200'
* index: string, // 'my-index'
* mappings: {
* properties: Object<(field string)=>({
* type: 'integer'|'keyword'|'text'|'boolean'|'binary'|'geo_point',
* })>
* },
* settings: {
* number_of_shards: number, // 1
* number_of_replicas: number, // 1
* },
* }) -> ElasticsearchIndex
* ```
*/
const ElasticsearchIndex = function (options) {
this.http = new Http(`${options.node}/${options.index}`)
this.ready = this.http.head('/').then(tap.if(
not(eq(get('status'), 200)),
async () => {
const response = await this.http.put('/', {
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
...options.mappings && {
mappings: {
properties: options.mappings,
},
},
...options.settings && {
settings: {
index: options.settings,
},
},
}),
})
if (!response.ok) {
const error = new Error(await response.text())
error.httpStatusCode = response.status
throw error
}
},
))
return this
}
/**
* @name ElasticsearchIndex.prototype.refresh
*
* @synopsis
* ```coffeescript [specscript]
* new ElasticsearchIndex(options).refresh() -> Promise<HttpResponse>
* ```
*
* @description
* https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-refresh.html
*/
ElasticsearchIndex.prototype.refresh = function refresh() {
return this.http.get('/_refresh')
}
/**
* @name ElasticsearchIndex.prototype.delete
*
* @synopsis
* ```coffeescript [specscript]
* new ElasticsearchIndex(options).delete() -> Promise<HttpResponse>
* ```
*
* @description
* https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-delete.html
*/
ElasticsearchIndex.prototype.delete = function _delete() {
return this.http.delete('/')
}
/**
* @name ElasticsearchIndex.prototype.indexDocument
*
* @synopsis
* ```coffeescript [specscript]
* new ElasticsearchIndex(options).indexDocument(
* elasticsearchDocument Object,
* options? {
* refresh: 'false'|'true'|'wait_for', // wait_for - wait for changes to be visible before replying
* },
* ) -> Promise<HttpResponse>
* ```
*/
ElasticsearchIndex.prototype.indexDocument = function indexDocument(
elasticsearchDocument, options,
) {
return this.http.post(`/_doc?${querystring.stringify({
refresh: get('refresh', 'false')(options),
})}`, {
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(elasticsearchDocument),
})
}
/**
* @name ElasticsearchIndex.prototype.updateDocument
*
* @synopsis
* ```coffeescript [specscript]
* newn Elasticsearch(options).updateDocument(
* elasticsearchDocumentId string,
* documentUpdate Object,
* options {
* refresh: 'false'|'true'|'wait_for', // wait_for - wait for changes to be visible before replying
* retry_on_conflict: number, // how many times operation should be retried when a conflict occurs. Default: 0
* },
* ) -> Promise<HttpResponse>
* ```
*/
ElasticsearchIndex.prototype.updateDocument = function updateDocument(
elasticsearchDocumentId, documentUpdate, options,
) {
return this.http.post(`/_update/${elasticsearchDocumentId}?${
querystring.stringify({
...pick(['refresh', 'retry_on_conflict'])(options),
})
}`, {
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
doc: documentUpdate,
}),
})
}
/**
* @name ElasticsearchIndex.prototype.getDocument
*
* @synopsis
* ```coffeescript [specscript]
* ElasticsearchIndex(options).getDocument(
* elasticsearchDocumentId string,
* options {
* refresh: 'false'|'true'|'wait_for', // wait_for - wait for changes to be visible before replying
* },
* ) -> Promise<HttpResponse>
* ```
*/
ElasticsearchIndex.prototype.getDocument = function getDocument(
elasticsearchDocumentId, options,
) {
return this.http.get(`/_doc/${elasticsearchDocumentId}?${
querystring.stringify({
...pick(['refresh'])(options),
})
}`)
}
/**
* @name ElasticsearchIndex.prototype.query
*
* @synopsis
* ```coffeescript [specscript]
* new ElasticsearchIndex(options).query(
* dsl Object,
* options? {
* size: number,
* from: number,
* to: number,
* },
* )
* ```
*/
ElasticsearchIndex.prototype.query = function query(dsl, options) {
return this.http.post('/_search', {
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: dsl,
...pick(['size', 'from', 'to'])(options)
}),
})
}
/**
* @name ElasticsearchIndex.prototype.term
*
* @synopsis
* ```coffeescript [specscript]
* newn Elasticsearch(options).term(
* termDSL {
* [field string]: {
* value: string,
* boost?: number,
* },
* },
* options? {
* size: number,
* from: number,
* to: number,
* },
* ) -> Promise<HttpResponse>
* ```
*
* @description
* https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html
*/
ElasticsearchIndex.prototype.term = function term(termDSL, options) {
return this.query({ term: termDSL }, options)
}
/**
* @name ElasticsearchIndex.prototype.match
*
* @synopsis
* ```coffeescript [specscript]
* ElasticsearchIndex(options).match(
* matchDSL {
* [field string]: string
* operator: 'OR'|'AND',
* },
* options? {
* size: number,
* from: number,
* to: number,
* },
* ) -> Promise<HttpResponse>
* ```
*
* @description
* https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html
*
* ```javascript
* const myIndex = new ElasticsearchIndex({
* node: 'http://localhost:9200/',
* index: 'my-index',
* })
*
* myIndex.match(
* { myField: 'this is a test' },
* { size: 100 },
* )
* ```
*/
ElasticsearchIndex.prototype.match = function match(matchDSL, options) {
return this.query({ match: matchDSL }, options)
}
/**
* @name ElasticsearchIndex.prototype.multiMatch
*
* @synopsis
* ```coffeescript [specscript]
* new ElasticsearchIndex(options).multiMatch(
* multiMatchDSL {
* query: string, // the querystring, e.g. 'this is a test'
* fields: Array<string>, // the fields to be queried, e.g. ['subject', 'message']
* type: // determines internal execution. results may vary
* 'best_fields' // (default) finds documents which may match any field, but uses `_score` from the best field
* |'most_fields' // finds documents which may match any field and combines `_score` from each field
* |'cross_fields' // treat fields with same analyzer as if they were one big field
* |'phrase' // run a `match_phrase` query on each field and use the `_score` from the best field
* |'phrase_prefix' // run a `match_phrase_prefix` query on each field and use the `_score` from the best field
* |'bool_prefix' // create a `match_bool_prefix` query on each field and combine the `_score` from each field
* },
* options? {
* size: number,
* from: number,
* to: number,
* },
* ) -> Promise<HttpResponse>
* ```
*
* @description
* https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-multi-match-query.html
*
* TODO https://www.elastic.co/guide/en/elasticsearch/reference/7.x/query-dsl-match-bool-prefix-query.html
*/
ElasticsearchIndex.prototype.multiMatch = function multiMatch(
multiMatchDSL, options
) {
return this.query({ multi_match: multiMatchDSL }, options)
}
/**
* @name ElasticsearchIndex.prototype.bool
*
* @synopsis
* ```coffeescript [specscript]
* new ElasticsearchIndex(options).bool(
* boolDSL {
* must?: Array|DSL, // clause (query) must appear, contributes to score
* filter?: Array|DSL, // clause (query) must appear, does not contribute to score
* should?: Array|DSL, // clause (query) _should_ appear, contributes to score
* must_not?: Array|DSL, // clause (query) must not appear, ignores scoring
* },
* options? {
* size: number,
* from: number,
* to: number,
* },
* ) -> Promise<HttpResponse>
* ```
*
* @description
* https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html
*/
ElasticsearchIndex.prototype.bool = function bool(boolDSL, options) {
return this.query({ bool: boolDSL }, options)
}
/**
* @name ElasticsearchIndex.prototype.disMax
*
* @synopsis
* ```coffeescript [specscript]
* new ElasticsearchIndex(options).disMax(
* disMaxDSL {
* queries: Array<DSL>,
* tie_breaker?: number, // [0, 1.0] used to increase relevance scores of documents matching multiple query clauses
* },
* options? {
* size: number,
* from: number,
* to: number,
* },
* ) -> Promise<HttpResponse>
* ```
*
* @description
* https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-dis-max-query.html
*/
ElasticsearchIndex.prototype.disMax = function disMax(disMaxDSL, options) {
return this.query({ dis_max: disMaxDSL }, options)
}
/**
* @name ElasticsearchIndex.prototype.functionScore
*
* @synopsis
* ```coffeescript [specscript]
* new ElasticsearchIndex(options).functionScore(
* functionScoreDSL {
* query: DSL,
* boost?: number, // boost for the whole query
* functions?: Array<{
* filter: DSL,
* weight?: number, // multiplies score in final computed score for a document
* script_score?: {
* script: {
* source: string, // Elasticsearch script expression, e.g. `Math.log(2 + doc['my-int'].value)`
* params?: Object,
* },
* },
* random_score?: {}|{ // provide seed and field for reproducible scores
* seed: number,
* field: string, // e.g. '_seq_no' (builtin)
* },
* field_value_factor?: {
* field: string, // field in document e.g. 'my-field'
* factor?: number, // multiply field value
* modifier?: // modify field value, default 'none'
* 'none' // no multiplier
* |'log' // common log
* |'log1p' // add 1 then common log
* |'log2p' // add 2 then common log
* |'ln' // natural log
* |'ln1p' // add 1 then natural log
* |'ln2p' // add 2 then common log
* |'square' // ^2
* |'sqrt' // square root
* |'reciprocal', // 1/x
* missing: number, // value to use in case of missing field
* },
* ['linear'|'exp'|'gauss']: { // decay function to use
* [field string]: { // Note: only numeric, date, and geo_point are supported
* origin: number|string, // origin for calculating distance. Must be given as a number for numeric field, date for date fields, and geo point for geo fields
* scale: number|string, // distance from origin + offset at which computed score == `decay` parameter.
* // geo: default unit meters [m] (e.g. 10m)
* // date: default milliseconds [ms] (e.g. 1h, 10d)
* offset: number|string, // only compute decay function for documents with a distance greater than this parameter, default 0
* decay: number, // defines how documents are scored at the distance given in `scale`. Default 0.5
* },
* multi_value_mode: // for multi-value fields, determine which value to use for calculating distance
* 'min' // use minimum computed distance
* |'max' // use maximum computed distance
* |'avg' // use average of computed distances
* |'sum' // use sum of all distances
* },
* }>
* max_boost?: number, // maximum a document's score can be boosted
* score_mode?: // specify how individual computed scores are combined
* 'multiply' // scores are multiplied (default)
* |'sum' // add scores
* |'avg' // average scores
* |'first' // first function that has a matching filter is applied
* |'max' // max of scores
* |'min', // min of scores
* boost_mode?: // specify how final computed score is combined with score of the query
* 'multiply' // query score and function score are multiplied (default)
* |'replace' // only function score is used, query score is ignored
* |'sum' // add query score and function score
* |'avg' // add query score and function score
* |'max' // maximum of query score and function score
* |'min', // minimum of query score and function score
* },
* options? {
* size: number,
* from: number,
* to: number,
* }
* ) -> Promise<HttpResponse>
* ```
*
* @description
* https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html
*/
ElasticsearchIndex.prototype.functionScore = function functionScore(
functionScoreDSL, options,
) {
return this.query({ function_score: functionScoreDSL }, options)
}
module.exports = ElasticsearchIndex