【问题标题】:Elasticsearch show only the name of all indices with node jsElasticsearch 仅显示节点 js 的所有索引的名称
【发布时间】:2016-12-27 22:22:10
【问题描述】:

我正在使用带有节点 js 的 ejs 框架。我可以获取 json 格式的所有索引名称。但我想要的只是索引的名称。我的代码如下-

var client = require('../routes/Connection.js');

//display all indexes
module.exports.allIndexes = function (searchData, callback) {
    client.indices.getAliases({
        index: "_all",
        level: "indices"
    }, function (error, response, status) {
        if (error) {
            console.log("search error: " + error)
        }
        else {
            //callback(response);---> this works
            callback(response.hits.hits); // ---> this doesn't
        }
    });
}

如果我在回调中使用响应,我会得到以下输出:

{
  "index-1": {
    "aliases": {}
  },
  "index-2": {
    "aliases": {}
  },
  "index-3": {
    "aliases": {}
  },
  "index-4": {
    "aliases": {}
  }
}

当我在回调中使用 response.hits.hits 时,我收到错误:“无法读取未定义的属性 'hits'”。我只想将索引名称显示为列表。仅供参考,在前端,我将响应说为“结果”:

        <h1>Index</h1>
        <% for(var i=0; i < results.length; i++) { %>
          <%= results[i].indices %>
        <% } %>

当然什么也没显示。

edit_1:

我按如下方式导入模块: 在我的index.js:

router.post('/indexes', function (req, res) {
    elasticModule.allIndexes(req.body, function (data) {
        res.render('elasticGui', { title: 'Elasticsearch GUI', results: data });
    });
});

【问题讨论】:

  • 你在哪里导入第一个模块?向我们展示你是如何做到的。
  • 还要检查您的响应参数中的response.errors 属性。
  • @jstice4all 我已经编辑了我的问题并补充说,请看一下,谢谢

标签: javascript node.js elasticsearch ejs


【解决方案1】:

查看您的响应结构时

{
  "index-1": {
    "aliases": {}
  },
  "index-2": {
    "aliases": {}
  },
  "index-3": {
    "aliases": {}
  },
  "index-4": {
    "aliases": {}
  }
}

你没有看到任何hits,是吗?所以response.hits 是未定义的,当尝试从response.hits 中引用hits 时会发生错误

您只需要像这样更改您的代码:

callback(Object.keys(response));

然后在您的视图中,您可以像这样遍历该数组:

    <% results.forEach(function(index) { %>
      <%= index %>
    <% }); %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2017-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多