This repository was archived by the owner on Jan 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathreindex.js
103 lines (85 loc) · 2.42 KB
/
reindex.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
/* eslint-disable no-console */
'use strict';
const Promise = require('bluebird');
const assert = require('assert');
const client = require('../config').elasticsearch;
const indexers = require('./indexers');
function runIndexer(indexDefinition, alias, indexer) {
const index = uniqueIndexName(alias);
const mapping = Object.assign(
{},
indexDefinition,
{ index }
);
return Promise.resolve()
.then(() => client.indices.create(mapping))
.then(() => indexer(index))
.catch((err) => removeIndexes([index]).then(() => { throw err; }))
.then(() => updateAlias(index, alias))
.catch((err) => {
console.error(err);
process.exit(-1);
});
}
function uniqueIndexName(alias) {
const date = new Date();
const indexSuffix = `${date.toISOString().slice(0, 10)}_${date.getTime()}`;
return `${alias}_${indexSuffix}`;
}
function updateAlias(index, alias) {
let indexesToRemove;
return Promise.resolve()
.then(() => client.indices.getAlias({ name: alias }))
.catch(ignoreESError(404))
.then((oldAliases) => {
if (oldAliases) {
indexesToRemove = Object.keys(oldAliases);
}
})
.then(() => client.indices.updateAliases({
body: {
actions: [
{ remove: { index: '*', alias } },
{ add: { index, alias } },
],
},
}))
.then(() => removeIndexes(indexesToRemove));
}
function ignoreESError(statusCode) {
return (err) => {
if (err.status !== statusCode) {
throw err;
}
};
}
function removeIndexes(indexes) {
let result;
if (indexes) {
console.log('Removing indexes:', indexes.join(', '));
result = client.indices.delete({ index: indexes, ignore: 404 });
}
return result;
}
function indexersToRun() {
const argv = process.argv;
const knownIndexers = Object.keys(indexers);
let result = knownIndexers;
if (argv.length > 2) {
const potentialIndexers = argv.slice(2);
const unknownIndexers = potentialIndexers.filter((idx) => knownIndexers.indexOf(idx) === -1);
const msg = `Unknown indexers: ${unknownIndexers.join(', ')}. Valid indexers are: ${knownIndexers.join(', ')}.`;
assert.deepEqual(unknownIndexers.length, 0, msg);
result = potentialIndexers;
}
return result;
}
Promise.each(indexersToRun(), (key) => {
const indexer = indexers[key];
return runIndexer(
indexer.index,
indexer.alias,
indexer.indexer
);
})
.then(() => process.exit());