Sending requests to Elasticsearch with axios

Viewed 12092

I'm working on a react app which needs to fetch data from elsaticsearch. In frontend, actually I'm trying to use axios to do the request:

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. The above query actually works inside kibana. However, the above query returns all the documents inside my-type, what am I doing wrong here?

4 Answers

Just use .post()

From the 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

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