This repository has been archived by the owner on Jul 13, 2023. It is now read-only.
/
ElsaticHelper.py
282 lines (237 loc) · 7.58 KB
/
ElsaticHelper.py
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
#!/usr/bin/python3
# coding: utf-8
# author: 9ian1i https://github.com/Qianlitp
import time
import logging
from elasticsearch5 import Elasticsearch, helpers
from tools.common.Logger import logger
from tools.common.common import datetime_now_obj, get_n_min_ago
from settings.database_config import ElasticConfig
logging.getLogger("elasticsearch").setLevel(logging.ERROR)
class ElasticHelper(object):
def __init__(self):
self.es = Elasticsearch(ElasticConfig.uri)
self._multi_search_results = []
self.bulk_task_queue = []
self.bulk_last_time = datetime_now_obj()
def delay_index(self, body, index, doc_type):
self.bulk_task_queue.append({
"index": {"_index": index, "_type": doc_type}
})
self.bulk_task_queue.append(body)
if self._can_do_bulk():
self.bulk(body=self.bulk_task_queue, index=index, doc_type=doc_type)
self.bulk_task_queue = []
self.bulk_last_time = datetime_now_obj()
def _can_do_bulk(self):
# 任务队列超过100条数据
if len(self.bulk_task_queue) > 100:
return True
# 时间间隔超过1分钟
if get_n_min_ago(1) > self.bulk_last_time:
return True
return False
def index(self, body, index, doc_type):
self.es.index(body=body, index=index, doc_type=doc_type)
def bulk(self, body, index, doc_type):
self.es.bulk(body=body, index=index, doc_type=doc_type)
def scan(self, body, index, doc_type):
return helpers.scan(self.es, query=body, index=index, doc_type=doc_type, preserve_order=True)
def search(self, body, index, doc_type):
try:
rsp = self.es.search(body=body, index=index, doc_type=doc_type, request_timeout=100)
if rsp.get("error"):
logger.error(rsp.get("error").get("reason"))
return
return rsp
except Exception as e:
print(body)
logger.error("es search error: " + str(e) + index)
def count(self, body, index, doc_type):
return self.es.count(index=index, doc_type=doc_type, body=body, request_timeout=100)
def delete_index(self, index):
return self.es.indices.delete(index=index)
def put_template(self, name, body, **kwargs):
return self.es.indices.put_template(name=name, body=body, create=True, **kwargs)
def exists_template(self, name, **kwargs) -> bool:
return self.es.indices.exists_template(name=name, **kwargs)
def delete_template(self, name, **kwargs):
return self.es.indices.delete_template(name=name, **kwargs)
def get_template(self, name, **kwargs):
return self.es.indices.get_template(name=name, **kwargs)
def wait_log_in_database(self, computer_name, record_number):
"""
因为消息队列和入库ES是分开进行的,所以可能会出现当消费到某条日志时,ES还没入库,所以需要检查同步
"""
count = 0
query = {
"query": get_must_statement(
get_term_statement("computer_name", computer_name),
get_term_statement("record_number", record_number)
),
"_source": False,
"size": 1
}
while True:
try:
rsp = self.es.search(body=query,
index=ElasticConfig.event_log_index,
doc_type=ElasticConfig.event_log_doc_type,
request_timeout=100)
if rsp.get("error"):
logger.error(rsp.get("error").get("reason"))
break
if len(rsp["hits"]["hits"]) > 0:
return rsp["hits"]["hits"][0]["_id"]
time.sleep(2)
# 最多等5次,即 2 * 5 = 10秒
if count == 10:
break
count += 1
except Exception as e:
logger.error("es wait_log_in_database search error: " + str(e))
break
def multi_search(self, body, index, doc_type):
try:
rsp = self.es.msearch(body=body,
index=index,
doc_type=doc_type,
request_timeout=100)
if rsp.get("error"):
logger.error(rsp.get("error").get("reason"))
return
return rsp
except Exception as e:
logger.error("es msearch error: " + str(e))
def get_time_range(compare, time, time_zone_offset=False):
if time_zone_offset:
return {
"constant_score": {
"filter": {
"range": {
"@timestamp": {
compare: time,
"time_zone": "+08:00"
}
}
}
}
}
else:
return {
"constant_score": {
"filter": {
"range": {
"@timestamp": {
compare: time,
}
}
}
}
}
def get_range_statement(field, compare, time):
return {
"constant_score": {
"filter": {
"range": {
field: {
compare: time,
}
}
}
}
}
def get_term_statement(field_name, value):
return {
"constant_score": {
"filter": {
"term": {
field_name: value
}
}
}
}
def get_must_statement(*args):
return {
"bool": {
"must": [*args]
}
}
def get_should_statement(*args):
return {
"bool": {
"should": [*args]
}
}
def get_terms_statement(field_name, value):
return {
"constant_score": {
"filter": {
"terms": {
field_name: value
}
}
}
}
def get_must_not_statement(statement):
return {
"bool": {
"must_not": statement
}
}
def get_sort_statement(field, order):
return {
field: order
}
def get_aggs_statement(name, aggs_type, field, size=1000000):
return {
name: {
aggs_type: {
"field": field,
"size": size
}
}
}
def get_double_aggs_statement(name1, aggs_type1, field1, name2, aggs_type2, field2):
return {
name1: {
aggs_type1: {
"field": field1,
"size": 1000000
},
"aggs": {
name2: {
aggs_type2: {
"field": field2,
"size": 1000000
}
}
}
}
}
def get_wildcard_statement(field, value):
return {
"constant_score": {
"filter": {
"wildcard": {
field: value
}
}
}
}
def get_match_must_all(field, value):
"""
match 查询,对于 text 字段分词忽略大小写
"""
return {
"constant_score": {
"filter": {
"match": {
field: {
"query": value,
"operator": "and"
}
}
}
}
}