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

时间:2016-12-29 13:41:21

标签: c# elasticsearch elasticsearch-net

我想检查与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() }
        };
    }

当我执行上面的方法时,抛出异常并收到此消息:

  

嗅探群集状态失败。

我该怎么做才能检查是否建立了与Elasticsearch的连接?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

Nest IElasticClient界面为此提供了Ping方法