from elasticsearch import Elasticsearch
from pecan import conf

es_client = None


def init(server_url):
    global es_client
    es_client = Elasticsearch(server_url)


def server_is_reachable():
    res = es_client.info()
    return res.get('status') == 200


def refresh():
    es_client.indices.refresh(index=conf.search.index)


def index_mail(mail):
    resp = es_client.index(index=conf.search.index,
                           body=mail.flattened,
                           doc_type='mail',
                           id=mail.brief.id)
    if not resp.get('created'):
        raise RuntimeError('Error when indexing mail id "%s"' % mail.brief.id)


def get_recently_modified(offset, limit):
    res = es_client.search(index=conf.search.index,
                           doc_type='mail',
                           from_=offset,
                           size=limit,)['hits']['hits']
    return [x['_source'] for x in res]

@@ -32,16 +32,32 @@
 icsearch
+, TransportError
 %0Afrom pe
@@ -706,19 +706,47 @@
 t, limit
-):%0A
+, retry_count=3):%0A    try:%0A    
     res 
@@ -808,32 +808,36 @@
                 
+    
 doc_type='mail',
@@ -829,32 +829,36 @@
 oc_type='mail',%0A
+    
                 
@@ -909,16 +909,20 @@
         
+    
 size=lim
@@ -946,22 +946,25 @@
 s'%5D%0A    
+  
-return
+  res =
  %5Bx%5B'_so
@@ -984,8 +984,180 @@
 in res%5D%0A
+    except TransportError:%0A        if retry_count %3E 0:%0A            res = get_recently_modified(offset, limit, retry_count-1)%0A        else:%0A            raise%0A    return res%0A

Add retries