[英]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.