# HG changeset patch
# User Samuel Trégouët <samuel.tregouet@logilab.fr>
# Date 1488464822 -3600
#      Thu Mar 02 15:27:02 2017 +0100
# Node ID a6137bc159fbd982338eb65df52208c14f907b14
# Parent  3d097513f4dd18e7be03dd4d6e5793cb78441d39
[hook] handle delete entity

diff --git a/hooks.py b/hooks.py
--- a/hooks.py
+++ b/hooks.py
@@ -39,7 +39,7 @@
 
     __regid__ = 'elasticsearch.contentupdatetoes'
     __select__ = hook.Hook.__select__ & score_entity(entity_indexable)
-    events = ('after_update_entity', 'after_add_entity')
+    events = ('after_update_entity', 'after_add_entity', 'after_delete_entity')
     category = 'es'
 
     def __call__(self):
@@ -76,22 +76,28 @@
             log.error('no connection to ES (not configured) skip ES indexing')
             return
         for entity in self.get_data():
+            kwargs = dict(index=indexer.index_name,
+                          id=entity.eid,
+                          doc_type=entity.cw_etype)
+            if self.cnx.deleted_in_transaction(entity.eid):
+                try:
+                    # TODO option for async ?
+                    es.delete(**kwargs)
+                except (ConnectionError, ProtocolError):
+                    log.debug('Failed to index in hook, could not connect to ES')
+                continue
             rql = fulltext_indexable_rql(entity.cw_etype,
                                          entity._cw.vreg.schema,
                                          eid=entity.eid)
             indexable_entity = self.cnx.execute(rql).one()
             serializer = indexable_entity.cw_adapt_to('IFullTextIndexSerializable')
-            json = serializer.serialize()
+            kwargs['body'] = json = serializer.serialize()
+            if json.get('parent'):
+                kwargs['parent'] = json.pop('parent')
+            else:  # TODO only for types that have parents
+                kwargs['routing'] = entity.eid
             try:
                 # TODO option pour coté async ? thread
-                kwargs = dict(index=indexer.index_name,
-                              id=entity.eid,
-                              doc_type=entity.cw_etype,
-                              body=json)
-                if json.get('parent'):
-                    kwargs['parent'] = json.pop('parent')
-                else:  # TODO only for types that have parents
-                    kwargs['routing'] = entity.eid
                 es.index(**kwargs)
             except (ConnectionError, ProtocolError):
                 log.debug('Failed to index in hook, could not connect to ES')