Express.js elasticsearch查询不起作用

时间:2014-08-02 19:29:50

标签: javascript node.js express elasticsearch

我正在尝试构建一个Express.js应用程序来查询在不同服务器上运行的弹性搜索。我创建了一个快速脚手架应用程序,我唯一改变的是routes/index.js。我将其更改为如下所示:

var express = require('express');
var router = express.Router();

var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
  host: 'http://SERVERDNS.com:9200/'
});

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});

router.get('/search', function(req, res) {
  var wut =       client.search({
          index:"test-papers-es",
          type:"test-papers-es",
          body: {query:
                 {"match": req.query}
                }
      });
  console.log(wut);
  res.send(wut);                                                                                                                                                  
  console.log(wut);
  console.log(req.query);
});
module.exports = router;

问题是,当我发送这样的查询时:

http://SERVERDNS.com:3000/search?title=gene

我没有得到回复(我期待JSON)。我的client.search(console.log)代码的var wut是:

{ _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined,
  _settledValue: undefined,
  _boundTo: undefined,
  abort: [Function: abortRequest] } 

我的req.query看起来像这样:{ title: 'gene' }

知道我做错了什么?

1 个答案:

答案 0 :(得分:3)

.search不同步。你不能只是调用它并期望在下一行得到答案。 API使用promises,如下所述:http://www.elasticsearch.org/guide/en/elasticsearch/client/javascript-api/current/quick-start.html#_say_hello_to_elasticsearch

举个例子:

client.search({
  q: 'pants'
}).then(function (body) {
  var hits = body.hits.hits;
}, function (error) {
  console.trace(error.message);
});