gpt4 book ai didi

node.js - 使用 HTTP 模块在 Node.js 上查询 ElasticSearch 忽略请求正文

转载 作者:可可西里 更新时间:2023-11-01 16:40:24 24 4
gpt4 key购买 nike

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 括起来,我会在尝试运行应用程序时收到“意外 token ”错误,所以我不知道如何使用 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();

最佳答案

所以 http.request 的 GET 请求不会尊重请求体,它总是会忽略请求体。所以,如果你想发送 body 到 elasticsearch,你应该发送一个 POST 请求。elasticsearch 以相同的方式处理 POST 和 GET 调用。

关于node.js - 使用 HTTP 模块在 Node.js 上查询 ElasticSearch 忽略请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47387761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com