diff --git a/hooks.py b/hooks.py index 680de326f545d419bf86d0431bf40873d8c0f3c4_aG9va3MucHk=..4e15941f6ce191d0f946955a8048e0249488f88d_aG9va3MucHk= 100644 --- a/hooks.py +++ b/hooks.py @@ -16,3 +16,43 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. """cubicweb-elasticsearch specific hooks and operations""" + +import logging + +from elasticsearch import Elasticsearch +from elasticsearch.exceptions import ConnectionError +from urllib3.exceptions import ProtocolError + +from cubicweb.server import hook +from cubicweb.predicates import score_entity +from cubes.elasticsearch.es import indexable_types + +log = logging.getLogger(__name__) + + +def entity_indexable(entity): + return entity.cw_etype in indexable_types(entity._cw.vreg.schema) + + +class ContentUpdateIndexES(hook.Hook): + + """detect content change and updates ES indexing""" + + __regid__ = 'elasticsearch.contentupdatetoes' + __select__ = hook.Hook.__select__ & score_entity(entity_indexable) + events = ('after_update_entity', 'after_add_entity') + category = 'es' + + def __call__(self): + locations = self._cw.vreg.config['elasticsearch-locations'] + index_name = self._cw.vreg.config['index-name'] + serializer = self.entity.cw_adapt_to('ISerializable') + json = serializer.serialize() + es = Elasticsearch(locations and locations.split(',') or None) + try: + # TODO option pour coté async ? + es.index(index=index_name, + doc_type=self.entity.cw_etype, + body=json) + except (ConnectionError, ProtocolError): + log.debug('Failed to index in hook, could not connect to ES')