-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelastic-export.js
executable file
·60 lines (52 loc) · 1.39 KB
/
elastic-export.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
#!/usr/bin/env node
const fs = require('fs');
const args = require('commander');
const elasticsearch = require('elasticsearch');
let defaultFilename = './elastic-export-index.json';
const getFileName = (indexName, out) => {
if (out === defaultFilename){
return './elastic-export-'+indexName+'.json';
}
return out;
};
args
.option('-H, --host <host>', 'Elastic search hostname', '127.0.0.1:9200')
.option('-I, --index <index>', 'Index name to export')
.option(
'-O, --out <file>',
'Output filename to save the result',
defaultFilename
)
.option('-L, --limit <limit>', 'Limit number of documents', 50)
.parse(process.argv);
if (!args.host) {
console.error('Host is required, -H <elastic hostname:port>');
process.exit();
}
if (!args.index) {
console.error('Index name is required, -I <index name>');
process.exit();
}
const client = new elasticsearch.Client({
host: args.host
});
let result = client.search({
index: args.index,
body: {
from: 0,
size: args.limit
}
});
result
.then(resp => {
let data = resp.hits.hits.map(item =>
Object.assign({}, { _id: item._id }, item._source)
);
let fileName = getFileName(args.index, args.out);
console.log(`Exported ${data.length} documents (${fileName})`);
fs.writeFileSync(fileName, JSON.stringify(data, null, 4));
// console.log(data);
})
.catch(err => {
console.error(err);
});