40

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")

2 Answers 2

65

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")
Sign up to request clarification or add additional context in comments.

5 Comments

I know its old post, but currently even I am looking for answer to the same question, but the problem with your answer is that when elasticsearch service is down es.ping() doesn't return False but returns the error
You can still wrap the call to es.ping within a try/catch block (like in the original question) and that would do the job as well.
The thing is the exceptions raised are chained. I mean the final exception raised is ConnectionError but it also raises NewConnectionError and ConnectionRefusedError before that, so which one should be handled. Because it still prints the stack trace of exception
Any error that hints that a ping could not even be made. So basically any connection errors
not working ` raise BadStatusLine(line) urllib3.exceptions.ProtocolError: ('Connection aborted.', BadStatusLine('This is not a HTTP port',))`
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.