-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathelasticsearch_client.js
109 lines (97 loc) · 2.39 KB
/
elasticsearch_client.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
import elasticsearch from 'elasticsearch';
import fs from 'fs';
import config from './config';
export function escapeLuceneSyntax(str) {
return [].map
.call(str, char => {
if (
char === '/' ||
char === '+' ||
char === '-' ||
char === '&' ||
char === '|' ||
char === '!' ||
char === '(' ||
char === ')' ||
char === '{' ||
char === '}' ||
char === '[' ||
char === ']' ||
char === '^' ||
char === '"' ||
char === '~' ||
char === '*' ||
char === '?' ||
char === ':' ||
char === '\\'
) {
return `\\${char}`;
}
return char;
})
.join('');
}
export function getClientVersion(response) {
let client = getClient();
return client.info().then(function (resp) {
return parseInt(resp.version.number.split('.')[0], 10);
}, function (err) {
response.send({
error: err
});
});
}
export function clientSearch(index, type, qs, request, response) {
let client = getClient();
client.search({
index,
type,
body: {
from: request.query.from || 0,
size: request.query.size || 100,
query: {
bool: {
must: [
{
query_string: { query: qs }
}
]
}
},
sort: [{ '@timestamp': { order: 'desc' } }]
}
}).then(function (resp) {
resp.hits.hits = resp.hits.hits.map(h => h._source);
response.send(resp.hits);
}, function (err) {
response.send({
error: err
});
});
}
export function getClient() {
let scheme = 'http';
let ssl_body = {};
if (config.get('es_ssl')) {
scheme = 'https';
ssl_body.rejectUnauthorized = true;
if (config.get('es_ca_certs')) {
ssl_body.ca = fs.readFileSync(config.get('es_ca_certs'));
}
if (config.get('es_client_cert')) {
ssl_body.cert = fs.readFileSync(config.get('es_client_cert'));
}
if (config.get('es_client_key')) {
ssl_body.key = fs.readFileSync(config.get('es_client_key'));
}
}
let auth = '';
if (config.get('es_username') && config.get('es_password')) {
auth = `${config.get('es_username')}:${config.get('es_password')}@`;
}
var client = new elasticsearch.Client({
hosts: [ `${scheme}://${auth}${config.get('es_host')}:${config.get('es_port')}`],
ssl: ssl_body
});
return client;
}