如何检查是否建立了与 Elasticsearch 的连接?

How to check if connection to Elasticsearch is established?

我想检查与Elasticsearch 数据库的连接是否正常。换句话说,我想 ping Elasticsearch。当我执行下面的代码时,抛出异常。

    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() }
        };
    }

当我执行上面的方法时,异常被抛出并且我得到这个消息:

Failed sniffing cluster state.

如何检查与 Elasticsearch 的连接是否已建立?

我遇到了同样的问题,我设法通过将 SniffingConnectionPool 更改为 SingleNodeConnectionPool 来解决这个问题。

Nest IElasticClient 接口为此提供了一个 Ping 方法