【问题标题】:How to properly list all elasticsearch indices from node.js如何正确列出 node.js 中的所有弹性搜索索引
【发布时间】:2020-01-25 21:50:30
【问题描述】:

在我的 node.js 应用程序中,我正在尝试构建所有弹性搜索索引的列表,并将此列表作为 JSON 发送到我的 Angular 应用程序。 我正在使用 elasticsearch.js 模块:

npm install elasticsearch

const elasticsearch = require('elasticsearch');
const client = new elasticsearch.Client({
  host: 'localhost:9200',
  log: 'trace'
});

然后,在我的 REST API 路由处理程序中,我正在 ping elasticsearch,并运行一个查询,假设返回所有索引:

indexRoutes.route('/').get(function (req, res) {
  client.ping({
    requestTimeout: 30000,
  }, function (error) {
    if (error) {
      console.error('elasticsearch cluster is down!');
    } else {
      console.log('All is well');
      client.cat.indices({format: 'json'})
          .then(console.log(index));
    }
  });
});

我假设,一旦 promise 被解决,就会有一个对象从它返回,所以我将该对象称为“索引”,但只会收到错误“索引未定义”。

获取此类列表并将结果分配给字符串的正确方法是什么?

【问题讨论】:

    标签: node.js elasticsearch elasticsearch.js


    【解决方案1】:
    client.cat.indices({format: 'json'})
    .then(console.log(index));
    

    应该是

    client.cat.indices({format: 'json'})
    .then((yourResponse) => {
      console.log(yourResponse);
    });
    

    或者更直接

    client.cat.indices({format: 'json'})
    .then(console.log); // notice I pass the function itself, I don't call it
    

    Promise.prototype.then 将回调作为参数 - 即当承诺最终实现时要调用的函数。您的代码所说的是“调用console.log 并将其返回值传递给Promise.prototype.then”。

    它崩溃是因为您没有将对象引用为index,而是访问了一个(显然)从未声明过的index 变量。

    在我展示的版本中,yourResponse 被声明为传递给Promise.prototype.then 的匿名箭头函数(形状为(...) => {...})的第一个(也是唯一一个)参数。所以yourResponse 在这里填充了.then 在其承诺履行时的调用结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-02
      • 2016-03-12
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      • 2022-01-18
      • 2018-08-20
      相关资源
      最近更新 更多