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();
答案 0 :(得分:0)
因此,http.request的GET请求不会尊重正文,它将始终忽略请求正文。因此,如果要将正文发送到elasticsearch,则应发送 POST 请求。 elasticsearch以相同的方式处理POST和GET调用。