如何检查ElasticSearch客户端是否已连接?

blo*_*ong 7 node.js elasticsearch

我正在使用elasticsearch-js(NodeJS),只要ElasticSearch正在运行,一切正常.但是,在尝试调用客户端的某个方法之前,我想知道我的连接是活的.我正在以一种同步的方式做事,但仅用于性能测试的目的(例如,检查我有一个空索引可以工作,摄取一些数据,查询数据).看一下这样的片段:

    var elasticClient = new elasticsearch.Client({
        host: ((options.host || 'localhost') + ':' + (options.port || '9200'))
    });
    // Note, I already have promise handling implemented, omitting it for brevity though
    var promise = elasticClient.indices.delete({index: "_all"});
    /// ...
Run Code Online (Sandbox Code Playgroud)

是否有一些机制可以在客户端配置上发送快速失败,或者我可以在客户端执行某些测试以确保在调用之前打开它delete

更新:2015-05-22
我不确定这是否正确,但也许尝试获取客户统计数据是合理的?

    var getStats = elasticClient.nodes.stats();
    getStats.then(function(o){
        console.log(o);
    })
    .catch(function(e){
        console.log(e);
        throw e;
    });
Run Code Online (Sandbox Code Playgroud)

通过node-debug,我看到当ElasticSearch关闭/无法访问时拒绝承诺:"Error: No Living connections".当它连接时,o我的处理程序似乎有关于连接状态的详细信息.这种方法是正确的还是有一种检查连接可行性的首选方法?

Jul*_* C. 15

获取统计数据可能是一个沉重的呼吁,只需确保您的客户端连接.您应该使用ping,请参阅第2个示例https://github.com/elastic/elasticsearch-js#examples

在启动时实例化elasticsearch-js客户端连接后,我们也在使用ping.

// example from above link
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
  host: 'localhost:9200',
  log: 'trace'
});

client.ping({
  // ping usually has a 3000ms timeout
  requestTimeout: Infinity,
  // undocumented params are appended to the query string
  hello: "elasticsearch!"
}, function (error) {
  if (error) {
    console.trace('elasticsearch cluster is down!');
  } else {
    console.log('All is well');
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 我相信这已经过时了 (4认同)