How to check if connection to Elasticsearch is established?

5.8k views Asked by At

I want to check if the connection to Elasticsearch database is ok. In other words I want to ping Elasticsearch. When I execute the code below, an exception is thrown.

    public async Task<HealthCheckResult> Execute()
    {
        if (_configuration.Nodes?.Length == 0)
        {
            await Task.Delay(1);
            return new HealthCheckResult("Connection Failed - Missing elasticsearch connection string")
            {
                ChildResults = new List<HealthCheckResult>() {new HealthCheckResult()}
            };
        }

        var node = new Uri(_configuration.Nodes.First());


        try
        {
            var connectionPool = new SniffingConnectionPool(new[] {node});
            var settings = new ConnectionConfiguration(connectionPool);
            var client = new ElasticLowLevelClient(settings);
            client.IndicesExists<string>("applications");
        }
        catch (Exception exception)
        {
            return new HealthCheckResult(exception.Message)
            {
                ChildResults = new List<HealthCheckResult>() { new HealthCheckResult() }
            };
        }

        return new HealthCheckResult("Connection Passed")
        {
            ChildResults = new List<HealthCheckResult>() { new HealthCheckResult() }
        };
    }

When I execute method above, exception is thrown and I get this message:

Failed sniffing cluster state.

What can I do to check if the connection to Elasticsearch is established?

2

There are 2 answers

0
StephenSpectre On BEST ANSWER

I was having the same problem and I managed to fix this by changing the SniffingConnectionPool to a SingleNodeConnectionPool.

0
Rob Willis On

The Nest IElasticClient interface provides a Ping method for this purpose