【发布时间】:2017-11-21 19:56:37
【问题描述】:
StackOverflow 社区。我已经开始使用 ES 和 Node.js,现在我正在尝试使用 HTTP 模块查询我的 ES 实例。
我正在尝试模仿以下 curl GET 请求:
curl -XGET 'localhost:9200/_search?pretty' -H 'Content-Type: application/json' -d'
{
"query": {
"multi_match" : {
"query": "this is a test",
"fields": [ "subject", "message" ]
}
}
}
'
像这样:
var options = {
hostname: '127.0.0.1',
port: 9200,
method: 'GET',
path: '/twitter/tweet/_search?pretty',
headers: {
'Content-Type': 'application/json',
'accept': 'application/json'
},
json: query
body: {
"query": {
"multi_match" : {
"query": "this is a test",
"fields": [ "subject", "message" ]
}
}
}
};
var req = http.request(options, function (response) {
var responseBody = "";
response.setEncoding("UTF-8");
response.on('data', function (chunk) {
responseBody += chunk;
});
response.on("end", function() {
fs.writeFile("responseBody.json", responseBody, function(err) {
if (err) {
throw err;
}
});
});
});
req.on("error", function(err) {
console.log(`problem with request: ${err.message}`);
});
req.end();
但是 ES 正在返回所有记录(就像我正在点击 _all 字段一样),而不仅仅是我正在传递的查询的命中。就像请求正文被忽略一样。
我也尝试通过将查询保存在变量中来传递它,然后简单地放入 json 键中:
json: query
但结果是一样的。如果我用单引号将 json 括起来,我会在尝试运行应用程序时收到“意外令牌”错误,所以我不知道如何使用 HTTP 模块成功地将查询传递给 Node.js:S.
编辑:
解决方法是在 request.write 方法中传递查询(JSON 字符串化):
req.write(query);
整个请求应该如下所示:
var query = JSON.stringify({
"query": {
"multi_match" : {
"query": "this is a test",
"fields": [ "subject", "message" ]
}
}
});
var options = {
hostname: '127.0.0.1',
port: 9200,
method: 'GET',
path: '/twitter/tweet/_search?pretty',
headers: {
'content-length': Buffer.byteLength(query),
'Content-Type': 'application/json'
}
};
var req = http.request(options, function (response) {
var responseBody = "";
response.setEncoding("UTF-8");
response.on('data', function (chunk) {
responseBody += chunk;
});
response.on("end", function() {
fs.writeFile("responseBody.json", responseBody, function(err) {
if (err) {
throw err;
}
});
});
});
req.on("error", function(err) {
console.log(`problem with request: ${err.message}`);
});
req.write(query);
req.end();
【问题讨论】:
标签: node.js http elasticsearch