如何使用python脚本检查elasticsearch中是否存在索引并对其执行异常处理?

May*_*Jha 10 python elasticsearch elasticsearch-plugin elasticsearch-net elasticsearch-2.0

如何使用python查询检查索引是否存在?

我将我的索引作为在查询外部分配的变量传递为: -

 i=int(datetime.datetime.now().strftime('%d'))+1
indextring="index"
for m in range (i-10,i):
    d = datetime.datetime(2016, 10, m, 18, 00).strftime('%Y-%m-%d')
    index1=datestring+d
    subfix="_"+datetime.datetime(2016, 10, m, 18, 00).strftime('%Y-%m-%d')
    es=Elasticsearch(['localhost:9200'])
    res = **es.search(index='{0}'.format(index1)**, doc_type="log",size=10000, from_=0, body={ "query": {
    "match": {
     ....Match condition follows
      }
    }
  }})
Run Code Online (Sandbox Code Playgroud)

现在,某些索引在特定日期不存在,但我希望该过程无论如何都要运行.当索引不存在时,我收到以下错误 - >

elasticsearch.exceptions.NotFoundError:TransportError(404,u'index_not_found_exception')

我不确定异常处理在elasticsearch中是如何工作的.

Chi*_*h25 31

你必须在索引上调用它.目前您正在使用搜索类的存在,它告诉您索引中是否存在给定文档而不是索引本身.

试试这个代码

if es.indices.exists(index="index"):
    Your code for search
Run Code Online (Sandbox Code Playgroud)

如果您想使用,还有更多选项.