Search code examples
elasticsearchelasticsearch-dsl

Elasticsearch '[bool] failed to parse field [filter]' exception


I am trying to solve parsing exception of my search query. I would like to get some help there :)

The exception reason: '[1:65] [bool] failed to parse field [filter]' message:'x_content_parse_exception'

My search:

data = (await this.elasticClient.search({
        index: Indexes.Measurements,
        size: 10000,
        body: {
          query: {
            bool: {
              filter: {
                terms: {
                  "MachineId": ["mo3", "mo2"]
                },
                range: {
                  '@timestamp': {
                    gte: `now-${lastMinutes}m`,
                    lte: 'now'
                  }
                }
              }
            },
          },
          sort : [{ "@timestamp" : "desc" }]
      }})).body.hits.hits.map(data => data._source);

Solution

  • You are missing [] around the filter clause, try out this below query

    data = (await this.elasticClient.search({
            index: Indexes.Measurements,
            size: 10000,
            body: {
              query: {
                bool: {
                  filter: [{
                    terms: {
                      "MachineId": ["mo3", "mo2"]
                    }},{
                    range: {
                      '@timestamp': {
                        gte: `now-${lastMinutes}m`,
                        lte: 'now'
                      }
                    }}]
                  }
                },
              },
              sort : [{ "@timestamp" : "desc" }]
          }})).body.hits.hits.map(data => data._source);
    

    In JSON format, it will be like this

    {
      "query": {
        "bool": {
          "filter": [
            {
              "terms": {
                "MachineId": [
                  "mo3",
                  "mo2"
                ]
              }
            },
            {
              "range": {
                "timestamp": {
                  "gte": "now-${lastMinutes}m",
                  "lte": "now"
                }
              }
            }
          ]
        }
      }
    }