On ElasticSearch, how to search based on the number of items in a field?

Viewed 102

On Elasticsearch I have a field named Itinerary that can contain multiple values (from 1 up to 6), for example in the picture below there's 2 items in the field.

"Itinerary": [
              {
                "Carrier": "LH",
                "Departure": "2021-07-04T06:55:00Z",
                "Number": "1493",
                "Arrival": "2021-07-04T08:40:00Z",
              },
              {
                "Carrier": "LH",
                "Departure": "2021-07-04T13:30:00Z",
                "Number": "422",
                "Arrival": "2021-07-04T16:05:00Z",
                }
              }
]

Is there a way to query the number of results that contains a certain amount of items in this particular field? Something like:

query: {
   match: {
       number_of_items_in_Itinerary_field : 4
          }
       }
1 Answers

You can achieve this by using a script query like this:

{
  "query": {
    "bool": {
      "filter": {
        "script": {
          "script": {
            "source": "doc['my_array_field'].length > params.param1",
            "lang": "painless",
            "params": {
              "param1": 1
            }
          }
        }
      }
    }
  }
}

Here is more Information on script queries: https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-script-query.html

and specifically on array types in painless scripts: https://www.elastic.co/guide/en/elasticsearch/painless/current/painless-operators-array.html

Related