Bhawan
Bhawan

Reputation: 2491

Match an array element in the array of json objects in elasticsearch

I am using elasticsearch-6.4.3

Let's say I have a sample document in the form:

{
"segment_details": [{
  "departure_airport_code": "DEL",
  "departure_time": "2019-10-10 03:00:00"
}, 
{
"departure_airport_code": "BOM",
"departure_time": "2019-10-11 23:00:00" 
}]
}

I wrote a query to get all the documents in which any of the elements of the segment_details has departure_airport_code of given code. The below query is working fine.

GET flight-cache_layers/_doc/_search
{
  "query": {
    "nested": {
      "path": "segment_details",
      "query": {
        "bool": {
          "must": [
            { "match": { 
              "segment_details.departure_airport_code": code }}
          ]
        }
      }
    }
  }
}

I want to write a query in which I want to check if any of the element of the segment_details contains any of the departure_airport_code in the given codes list.

GET flight-cache_layers/_doc/_search
{
  "query": {
    "nested": {
      "path": "segment_details",
      "query": {
        "bool": {
          "must": [
            { "match": { 
              "segment_details.departure_airport_code" IN codes }}  # something like this.
          ]
        }
      }
    }
  }
}

Upvotes: 0

Views: 1895

Answers (1)

jaspreet chahal
jaspreet chahal

Reputation: 9099

Nested Aggregation You can use a should clause where a text should match any of these values.

"query": {
    "nested": {
      "path": "segment_details",
      "query": {
        "bool": {
          "should": [
            {
              "match": {
                "FIELD": "TEXT"  --> replace field with your field and text with value
              }
            },
             {
              "match": {
                "FIELD": "TEXT"
              }
            }
          ]
        }
      }
    }
  }

If you are searching for exact words, you can use terms query

"query": {
    "nested": {
      "path": "segment_details",
      "query": {
        "bool": {
          "must": [
            {
              "terms": {
                "FIELD": [ --> replace field with your field and value array with values, you might need to use field.keyword as per your mapping 
                  "VALUE1",
                  "VALUE2"
                ]
              }
            }
          ]
        }
      }
    }
  }

Upvotes: 1

Related Questions