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

xwbd5t1u  于 2022-11-02  发布在  ElasticSearch
关注(0)|答案(2)|浏览(158)

如何使用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.异常.未找到错误:404,您访问的页面不存在。

我不确定ElasticSearch中的异常处理是如何工作的。

3qpi33ja

3qpi33ja1#

你必须在索引上调用它。目前你正在使用搜索类的exists,它告诉你给定的文档是否存在于索引中,而不是索引本身。
请尝试以下代码

if es.indices.exists(index="index"):
    Your code for search

如果要使用,还有更多选项。

bgtovc5b

bgtovc5b2#

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

检查索引列表是否可用

相关问题