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

31

如何使用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
      }
    }
  }})

现在,某些索引在特定日期不存在,但我希望该过程可以不考虑此问题而继续运行。当索引不存在时,我会收到以下错误消息-->

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

我不确定在elasticsearch中如何处理异常。


1
你应该尝试使用exists API调用来检查索引是否存在。 - Val
试过了,你能看一下我在tcarmet回复下面的评论吗? - Mayank Jha
2个回答

70
你需要在indices上调用它。目前你正在使用搜索类的exists,它告诉你给定的文档是否存在于索引中,而不是索引本身。
尝试这段代码
if es.indices.exists(index="index"):
    Your code for search

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


0
for i in index_list:
    if es.indices.exists(index=i):
        print("ok",i)
    else:
        print(i)

检查索引列表是否可用


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接