node.js - 如何正确列出 node.js 中的所有 Elasticsearch 索引

标签 node.js elasticsearch elasticsearch.js

在我的 node.js 应用程序中,我正在尝试构建所有 Elasticsearch 索引的列表,并将此列表作为 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 得到解决,就会有一个对象从它返回,所以我将该对象引用为“索引”,但只会得到错误“索引未定义”。

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

最佳答案

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

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

在我展示的版本中,yourResponse被声明为传递给 (...) => {...} 的匿名箭头函数(形状为 Promise.prototype.then)的第一个(也是唯一的)参数.所以yourResponse此处填充了 .then 的调用结果当它的 promise 实现时。

关于node.js - 如何正确列出 node.js 中的所有 Elasticsearch 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58102867/

相关文章:

javascript - 如何使用 elasticsearch.js 和 Angular 在 Elasticsearch 上搜索嵌套对象

node.js - 如何让等待 Action 完成,然后收到新消息?

javascript - 使用 css 选择器,如何使用它的类获取元素的第 n 个子元素

node.js - 使用 npm 安装 socket.io

android - 在数据写入数据库之前返回 Firebase 任务

apache-spark - 我可以将es.batch.write.retry.count设置为零值吗

python - Elasticsearch:具有多个字段的单个 "more-like-this"查询与具有单个字段的多个 "more-like-this"查询

elasticsearch - ElasticSearch中唯一聚合doc_count的计数