check elasticsearch connection status in python

Question:

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")
Asked By: user4005632

||

Answers:

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")
Answered By: Val

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
Answered By: Ikko
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.