-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.py
301 lines (251 loc) · 9.91 KB
/
index.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# -*- coding: utf-8 -*-
import json
from pyes.exceptions import NotFoundException
from trytond.model import ModelSQL, ModelView, fields
from trytond.pool import PoolMeta, Pool
from trytond.exceptions import UserError
__all__ = ['IndexBacklog', 'DocumentType', ]
__metaclass__ = PoolMeta
class IndexBacklog(ModelSQL, ModelView):
"""
Index Backlog
-------------
This model stores the documents that are yet to be sent to the
remote full text search index.
"""
__name__ = "elasticsearch.index_backlog"
record_model = fields.Char('Record Model', required=True, select=True)
record_id = fields.Integer('Record ID', required=True, select=True)
@classmethod
def create_from_records(cls, records):
"""
A convenience create method which can be passed multiple active
records and they would all be added to the indexing backlog. A check
is done to ensure that a record is not already in the backlog.
:param record: List of active records to be indexed
"""
vlist = []
for record in records:
if not cls.search([
('record_model', '=', record.__name__),
('record_id', '=', record.id),
], limit=1):
vlist.append({
'record_model': record.__name__,
'record_id': record.id,
})
return cls.create(vlist)
@staticmethod
def _build_default_doc(record):
"""
If a document does not have an `elastic_search_json` method, this
method tries to build one in lieu.
"""
return {
'rec_name': record.rec_name,
}
@classmethod
def update_index(cls, batch_size=100):
"""
Update the remote elastic search index from the backlog and
delete backlog entries once done.
To be scalable, this operation limits itself to handling the oldest
batch of records at a time. The batch_size can be optionally passed on
to this function call. This should be small enough for subsequent
transactions not to be blocked for a long time.
That depends on your specific implementation and index size.
"""
config = Pool().get('elasticsearch.configuration')(1)
conn = config.get_es_connection()
for item in cls.search_read(
[], order=[('id', 'DESC')], limit=batch_size,
fields_names=['record_model', 'record_id', 'id']):
Model = Pool().get(item['record_model'])
try:
record, = Model.search([('id', '=', item['record_id'])])
except ValueError:
# Record may have been deleted
try:
conn.delete(
config.index_name, # Index Name
config.make_type_name(Model.__name__), # Document Type
item['record_id']
)
except NotFoundException:
# This record was not there in elastic search too.
# Never mind!
pass
else:
if hasattr(record, 'elastic_search_json'):
# A model with the elastic_search_json method
data = record.elastic_search_json()
else:
# A model without elastic_search_json
data = cls._build_default_doc(record)
conn.index(
data,
config.index_name, # Index Name
config.make_type_name(record.__name__), # Document Type
record.id, # Record ID
)
finally:
# Delete the item since it has been sent to the index
cls.delete([cls(item['id'])])
class DocumentType(ModelSQL, ModelView):
"""
Elastic Search Document Type Definition
This will in future be used for the mapping too.
"""
__name__ = "elasticsearch.document.type"
name = fields.Char('Name', required=True)
model = fields.Many2One('ir.model', 'Model', required=True, select=True)
trigger = fields.Many2One(
'ir.trigger', 'Trigger', required=False, ondelete='RESTRICT'
)
mapping = fields.Text('Mapping', required=True)
@staticmethod
def default_mapping():
return '{}'
@classmethod
def __setup__(cls):
super(DocumentType, cls).__setup__()
# TODO: add a unique constraint on model
cls._buttons.update({
'update_mapping': {},
'reindex_all_records': {},
'get_default_mapping': {},
})
cls._error_messages.update({
'wrong_mapping': 'Mapping does not seem to be valid JSON',
})
@classmethod
def create(cls, document_types):
"Create records and make appropriate triggers"
# So that we don't modify the original data passed
document_types = [dt.copy() for dt in document_types]
for document_type in document_types:
document_type['trigger'] = cls._trigger_create(
document_type['name'],
document_type['model']
).id
return super(DocumentType, cls).create(document_types)
@classmethod
def write(cls, document_types, values):
"Update records and add/remove triggers appropriately"
Trigger = Pool().get('ir.trigger')
if 'trigger' in values:
raise UserError("Updating Trigger manually is not allowed!")
triggers_to_delete = []
for document_type in document_types:
triggers_to_delete.append(document_type.trigger)
values_new = values.copy()
# so that we don't change the original values passed to us
trigger = cls._trigger_create(
values_new.get('name', document_type.name),
values_new.get('model', document_type.model.id)
)
values_new['trigger'] = trigger.id
super(DocumentType, cls).write([document_type], values_new)
Trigger.delete(triggers_to_delete)
@classmethod
def delete(cls, document_types):
"Delete records and remove associated triggers"
Trigger = Pool().get('ir.trigger')
triggers_to_delete = [dt.trigger for dt in document_types]
super(DocumentType, cls).delete(document_types)
Trigger.delete(triggers_to_delete)
@classmethod
def _trigger_create(cls, name, model):
"""Create trigger for model
:param name: Name of the DocumentType used as Trigger name
:param model: Model id
"""
Trigger = Pool().get('ir.trigger')
Model = Pool().get('ir.model')
index_model = Model(model)
action_model, = Model.search([
('model', '=', cls.__name__),
])
return Trigger.create([{
'name': "elasticsearch_%s" % name,
'model': index_model.id,
'on_create': True,
'on_write': True,
'on_delete': True,
'action_model': action_model.id,
'condition': 'true',
'action_function': '_trigger_handler',
}])[0]
@classmethod
def _trigger_handler(cls, records, trigger):
"Handler called by trigger"
IndexBacklog = Pool().get('elasticsearch.index_backlog')
return IndexBacklog.create_from_records(records)
@classmethod
def validate(cls, document_types):
"Validate the records"
super(DocumentType, cls).validate(document_types)
for document_type in document_types:
document_type.check_mapping()
def check_mapping(self):
"""
Check if it is possible to at least load the JSON
as a check for its validity
"""
try:
json.loads(self.mapping)
except:
self.raise_user_error('wrong_mapping')
@classmethod
@ModelView.button
def reindex_all_records(cls, document_types):
"""
Reindex all of the records in this model
:param document_types: Document Types
"""
IndexBacklog = Pool().get('elasticsearch.index_backlog')
for document_type in document_types:
Model = Pool().get(document_type.model.model)
records = Model.search([])
# Performance speedups
index_backlog_create = IndexBacklog.create
model_name = Model.__name__
vlist = []
for record in records:
vlist.append({
'record_model': model_name,
'record_id': record.id,
})
index_backlog_create(vlist)
@classmethod
@ModelView.button
def get_default_mapping(cls, document_types):
"""
Tries to get the default mapping from the model object
"""
for document_type in document_types:
Model = Pool().get(document_type.model.model)
if hasattr(Model, 'es_mapping'):
cls.write(
[document_type], {
'mapping': json.dumps(Model.es_mapping(), indent=4)
}
)
else:
cls.raise_user_error(
"Model %s has no mapping specified" % Model.__name__
)
@classmethod
@ModelView.button
def update_mapping(cls, document_types):
"""
Update the mapping on the server side
"""
config = Pool().get('elasticsearch.configuration')(1)
conn = config.get_es_connection()
for document_type in document_types:
conn.indices.put_mapping(
config.make_type_name(document_type.model.model), # Type
json.loads(document_type.mapping), # Mapping
[config.index_name], # Index
)