简体   繁体   中英

check elasticsearch connection status in python

I am trying to connect elasticsearch in my local and I wonder how can I know the connection is successful or failed before continue to process: I wish it is possible with the way below I used but not(it returns too many values but all useless):

try:
    es = Elasticsearch(['http://localhost:9200/'], verify_certs=True)
except Exception as err:
    if "Connection refused" in err.message:
        logging.error("Connection failed")

I hope there is a way to check connection status like this:

if es == false:
    raise ValueError("Connection failed")

What you can do is call ping after creating the Elasticsearch instance, like this:

es = Elasticsearch(['http://localhost:9200/'], verify_certs=True)

if not es.ping():
    raise ValueError("Connection failed")

I had same urllib3.exceptions.ProtocolError issue, so made up for myself.

import requests
def isRunning(self):
    try:
        res = requests.get("http://localhost:9200/_cluster/health")
        if res.status_code == 200:
            if res.json()['number_of_nodes'] > 0:
                return True
        return False
    except Exception as e:
        print(e)
        return False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM