簡體   English   中英

使用 python elasticsearch 創建索引時如何處理 try catch 異常?

[英]How to handle try catch exception when creating an index with python elasticsearch?

如果索引已經存在,我會嘗試打印錯誤。 我使用 python 和 Elasticsearch。

import time,schedule
import requests
from elasticsearch import Elasticsearch 
import sys
import logging
import json
from datetime import datetime

es = elasticsearch.Elasticsearch('http:/ip:port',timeout=600)
settings = { "settings": {
                 "number_of_shards":1,
                  'number_of_replicas':0
                 },
      "mappings" : { 
           "document" : {
                "properties":{
                    "geo": {
                       "type": "geo_point"
                            }
                          }
                        } 
                     } 
                  }
try:
 es.indices.create(index = "spacestation", body=settings)
except Elasticsearch.ElasticsearchException as es1:
 print('Index already exists!!')

但我收到以下錯誤:

elasticsearch.exceptions.RequestError: RequestError(400, 'resource_already_exists_exception', 'index [spacestation/IlVCpABTSYmWVDVrGmTRMA] already exists')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "__main__.py", line 42, in <module>
except Elasticsearch.ElasticsearchException as es1:
AttributeError: type object 'Elasticsearch' has no attribute 'ElasticsearchException'

無論我的代碼是否正確,我都沒有收到此錯誤。 如果索引已經存在,我認為這不是打印錯誤的正確代碼。 請有人可以糾正我嗎? 謝謝

只需將您的代碼更改為:

from elasticsearch import Elasticsearch, RequestError
...


try:
  es.indices.create(index = "spacestation", body=settings)
except RequestError as es1:
  print('Index already exists!!')
  sys.exit(1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM