-
Notifications
You must be signed in to change notification settings - Fork 0
/
es.py
274 lines (234 loc) · 9.35 KB
/
es.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
from abc import ABC, abstractmethod
import logging
from elasticsearch import Elasticsearch, ElasticsearchException
class BaseElastic(ABC):
MAX_COUNT_SEARCH = 10000
DEFAULT_SCROLL = "1m"
def __init__(self, host, port, user=None, password=None, timeout='1s'):
self._id = '_id'
self._timeout = timeout
self.current_connection = None
try:
if not self.index_conf():
raise ElasticsearchException('Index is invalid')
if not host or not port:
raise ElasticsearchException('Please provide elastic server config')
elif user and password:
self.current_connection = Elasticsearch(host=host, port=port, http_auth=(user, password), )
else:
self.current_connection = Elasticsearch(host=host, port=port)
if self.current_connection and self.is_connected() and not self.exists() and self.mapping_conf():
self.init_mapping()
except ElasticsearchException as e:
raise ElasticsearchException(e)
@abstractmethod
def index_conf(self) -> str:
pass
@abstractmethod
def mapping_conf(self) -> dict:
return {}
@abstractmethod
def settings_conf(self) -> dict:
return {}
def get_connection(self):
"""
:rtype: Elasticsearch
"""
return self.current_connection
def is_connected(self):
if self.get_connection().ping():
return True
else:
return False
def exists(self):
if self.is_connected():
return self.get_connection().indices.exists(self.index_conf())
else:
return False
def init_mapping(self):
if self.is_connected():
body = {
'mappings': {
'_source': {
'enabled': True
},
'properties': self.mapping_conf()
}
}
if self.settings_conf():
body['settings'] = self.settings_conf()
self.get_connection().indices.create(index=self.index_conf(), body=body)
def index(self, data, refresh=True):
if self.is_connected():
if self._id in data:
id = data[self._id]
else:
id = None
result = self.get_connection().index(index=self.index_conf(), body=data, id=id, refresh=bool(refresh),
timeout=self._timeout)
if result and '_shards' in result and 'successful' in result['_shards'] \
and result['_shards']['successful'] == 1:
return True
return False
def update(self, index_id, data, refresh=True):
if self.is_connected() and self.get_connection().exists(index=self.index_conf(), id=index_id) and data:
body = {
'doc': data
}
result = self.get_connection().update(index=self.index_conf(), id=index_id, body=body,
refresh=bool(refresh), timeout=self._timeout)
if result and 'result' in result and (
(result['result'] == 'updated' and '_shards' in result and 'successful' in result['_shards'] and
result['_shards']['successful'] == 1)
or result['result'] == 'noop'
):
return True
return False
def delete(self, index_id, refresh=True):
result = False
if self.is_connected() and index_id:
if self.get_connection().exists(index=self.index_conf(), id=index_id):
result = self.get_connection().delete(index=self.index_conf(), id=index_id, refresh=bool(refresh),
timeout=self._timeout)
else:
logging.error('No data to delete.')
return result
def delete_by_params(self, data, refresh=True):
result = False
if self.is_connected() and data:
result = self.get_connection().delete_by_query(index=self.index_conf(), body=data, conflicts='proceed',
refresh=bool(refresh), timeout=self._timeout)
else:
logging.error('The parameter passed is not matched.')
return result
def bulk(self, data):
result = False
if self.is_connected() and data:
result = self.get_connection().bulk(body=data, index=self.index_conf())
else:
logging.error('The parameter passed is not matched.')
return result
def search(self, params):
result = []
total = 0
if self.is_connected() and self.exists():
if 'body' in params:
body = params['body']
else:
body = params
data = self.get_connection().search(index=self.index_conf(), body=body)
if 'hits' in data:
if 'total' in data['hits'] and 'value' in data['hits']['total']:
total = data['hits']['total']['value']
if 'hits' in data['hits']:
hits = data['hits']['hits']
step = 0
while step < len(hits):
if hits[step]:
result.append(hits[step])
step += 1
return {
'data': result,
'total': total
}
def scroll(self, params, offset, limit):
result = []
total = 0
if self.is_connected() and self.exists():
if 'body' in params:
body = params['body']
else:
body = params
search_data = self.get_connection().search(index=self.index_conf(), body=body,
scroll=self.DEFAULT_SCROLL, size=limit)
total = search_data['hits']['total']['value']
i = len(search_data['hits']['hits'])
if offset == 0:
data = search_data['hits']['hits']
else:
scroll_id = search_data['_scroll_id']
scroll_data = {}
while i <= offset:
scroll_data = self.get_connection().scroll(scroll_id=scroll_id, scroll=self.DEFAULT_SCROLL)
count = len(scroll_data['hits']['hits'])
if count > 0:
scroll_id = scroll_data['_scroll_id']
else:
break
i += count
data = scroll_data['hits']['hits'] if 'hits' in scroll_data and \
'hits' in scroll_data['hits'] else []
if data:
step = 0
while step < len(data):
if data[step]:
result.append(data[step])
step += 1
return {
'data': result,
'total': total
}
def scroll_all(self, params):
data = []
total = 0
if self.is_connected() and self.exists():
if 'body' in params:
body = params['body']
else:
body = params
search_data = self.get_connection().search(index=self.index_conf(), body=body,
scroll=self.DEFAULT_SCROLL, size=self.MAX_COUNT_SEARCH)
total = search_data['hits']['total']['value']
data += search_data['hits']['hits']
scroll_id = search_data['_scroll_id']
while True:
scroll_data = self.get_connection().scroll(scroll_id=scroll_id, scroll=self.DEFAULT_SCROLL)
count = len(scroll_data['hits']['hits'])
if count > 0:
data += scroll_data['hits']['hits']
scroll_id = scroll_data['_scroll_id']
else:
break
return {
'data': data,
'total': total
}
def advanced_search(self, params, offset=0, limit=MAX_COUNT_SEARCH):
if (offset + limit) <= self.MAX_COUNT_SEARCH:
params = {
**params,
"from": offset,
"size": limit
}
return self.search(params)
else:
return self.scroll(params, offset, limit)
def advanced_search_all(self, params, total=None):
if not total:
total = self.count(params)
if total <= self.MAX_COUNT_SEARCH:
params = {
**params,
"from": 0,
"size": total
}
return self.search(params)
else:
return self.scroll_all(params)
def count(self, params):
count = 0
if self.is_connected() and self.exists():
if 'body' in params:
body = params['body']
else:
body = params
if 'size' in body:
del body['size']
if 'from' in body:
del body['from']
if 'sort' in body:
del body['sort']
data = self.get_connection().count(index=self.index_conf(), body=body)
if 'count' in data:
count = data['count']
return count