使用 axios 向 Elasticsearch 发送请求

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 中有效。但是,上面查询returns里面的所有文件都是my-type,我这里哪里错了?

我认为以下应该可行。尽管 Axios READMEdata 专门针对 PUTPOSTPATCH 请求,但我在代码中没有看到任何强制执行此操作的内容,简化测试表明确实为 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 似乎允许 sending the request body in a parameter instead,也许正是因为这个问题。

这应该可以解决问题:

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 请求的一般限制。每 the documentation for XMLHttpRequest.send:

If the request method is GET or HEAD, the argument is ignored and request body is set to null.

试试这个

axios.get(`http://localhost:9200/my-index/my-type/_search?q=${_id:AV12n5KzsohD5gXzTnOr}`)
  .then((res) => {
    console.log(res);
});

只需使用.post()

来自 Elasticsearch docs

Both HTTP GET and HTTP POST can be used to execute search with body. Since not all clients support GET with body, POST is allowed as well

只是为了其他人如果他们来这里。以下方式对我有用:(不要注意示例数据)

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'
                }
              }
            }
          ]
        }
      }
    })
  })