[英]Sending requests to Elasticsearch with axios
I'm working on a react app which needs to fetch data from elsaticsearch.我正在开发一个需要从 elsaticsearch 获取数据的 React 应用程序。 In frontend, actually I'm trying to use axios to do the request:在前端,实际上我正在尝试使用 axios 来执行请求:
const query = {
query: {
match: {
"_id": "AV12n5KzsohD5gXzTnOr"
}
}
};
axios.get('http://localhost:9200/my-index/my-type/_search', query)
.then((res) => {
console.log(res);
});
I want to get the specific document with some ID.我想获取带有一些 ID 的特定文档。 The above query actually works inside kibana.上面的查询实际上在 kibana 中有效。 However, the above query returns all the documents inside my-type, what am I doing wrong here?但是,上面的查询返回了 my-type 中的所有文档,我在这里做错了什么?
I think the below should work.我认为以下应该有效。 Although the Axios README says that data
is specifically only for PUT
, POST
, and PATCH
requests, I didn't see anything in the code that enforces this, and a simplified test shows that the request body is indeed sent for GET
requests:尽管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);
});
EDIT编辑
Note that I've only tested this in Node.js, not in a browser.请注意,我只在 Node.js 中测试过这个,没有在浏览器中测试过。 Browsers may be less inclined to include request bodies with GET
requests.浏览器可能不太愿意在GET
请求中包含请求体。
EDIT 2编辑 2
Elasticsearch seems to allow sending the request body in a parameter instead , perhaps because of this very issue. Elasticsearch 似乎允许在参数中发送请求正文,这可能是因为这个问题。
This should do the trick:这应该可以解决问题:
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);
});
EDIT 3编辑 3
This does indeed seem to be a general restriction on making GET
requests in browsers.这确实似乎是在浏览器中发出GET
请求的一般限制。 Per the documentation for XMLHttpRequest.send :根据XMLHttpRequest.send 的文档:
If the request method is GET or HEAD, the argument is ignored and request body is set to null.如果请求方法是 GET 或 HEAD,则忽略该参数并将请求正文设置为 null。
try this试试这个
axios.get(`http://localhost:9200/my-index/my-type/_search?q=${_id:AV12n5KzsohD5gXzTnOr}`)
.then((res) => {
console.log(res);
});
Just for others if they come here.只是为了其他人,如果他们来到这里。 Following way worked for me: (Don't pay attention to sample data)以下方法对我有用:(不要注意样本数据)
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.