[英]Sending requests to Elasticsearch with axios
我正在开发一个需要从 elsaticsearch 获取数据的 React 应用程序。 在前端,实际上我正在尝试使用 axios 来执行请求:
const query = {
query: {
match: {
"_id": "AV12n5KzsohD5gXzTnOr"
}
}
};
axios.get('http://localhost:9200/my-index/my-type/_search', query)
.then((res) => {
console.log(res);
});
我想获取带有一些 ID 的特定文档。 上面的查询实际上在 kibana 中有效。 但是,上面的查询返回了 my-type 中的所有文档,我在这里做错了什么?
我认为以下应该有效。 尽管Axios README说data
仅针对PUT
、 POST
和PATCH
请求,但我在代码中没有看到任何强制执行此操作的内容,并且经过简化的测试表明请求正文确实是针对GET
请求发送的:
axios.get('http://localhost:9200/my-index/my-type/_search', {
data: JSON.stringify(query),
}).then((res) => {
console.log(res);
});
编辑
请注意,我只在 Node.js 中测试过这个,没有在浏览器中测试过。 浏览器可能不太愿意在GET
请求中包含请求体。
编辑 2
Elasticsearch 似乎允许在参数中发送请求正文,这可能是因为这个问题。
这应该可以解决问题:
axios.get('http://localhost:9200/my-index/my-type/_search', {
params: {
source: JSON.stringify(query),
source_content_type: 'application/json'
}
}).then((res) => {
console.log(res);
});
编辑 3
这确实似乎是在浏览器中发出GET
请求的一般限制。 根据XMLHttpRequest.send 的文档:
如果请求方法是 GET 或 HEAD,则忽略该参数并将请求正文设置为 null。
只需使用.post()
来自 Elasticsearch 文档
HTTP GET 和 HTTP POST 均可用于执行带正文的搜索。 由于并非所有客户端都支持带有正文的 GET,因此也允许使用 POST
试试这个
axios.get(`http://localhost:9200/my-index/my-type/_search?q=${_id:AV12n5KzsohD5gXzTnOr}`)
.then((res) => {
console.log(res);
});
只是为了其他人,如果他们来到这里。 以下方法对我有用:(不要注意样本数据)
axios({
url: 'your ES url',
method: 'POST',
timeout: 0,
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify({
query: {
bool: {
filter: [
{ match_all: {} },
{ match_phrase: { 'data.gateway': { query: 'gateway1' } } },
{ match_phrase: { 'data.sensor': { query: '10001' } } },
{ range: { 'data.dateTime': { lte: '2020-05-26 20:25:00' } } },
{
range: {
receivedInES: {
format: 'strict_date_optional_time',
gte: '2020-05-25T19:37:23.621Z',
lte: '2020-05-26T19:37:23.621Z'
}
}
}
]
}
}
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.