user2689782
user2689782

Reputation: 757

Elasticsearch bool query with nested as well as non-nested clauses

I have data with nested as well as non-nested components. I cannot remap the data, it is in production. Sample is

{
   "name":[
      "first":"Tom",
      "last":"Smith"
   ],
   "status":"married"
}

I need to query within nested as well as non-nested values . Ie, all entries who are not 'married' but whose first names are 'Tom'.

To do a query just for 'Tom', I would do

GET /_search
{
  "query": {
    "nested": {
      "path": "name",
      "query": {
        "bool": {
          "must": [
            { 
              "match" : {"name.first" : "Tom"}}
          ]
        }
      }
    }
  }
}

But how do I combine this with a must_not query on status(which is non nested)

Upvotes: 0

Views: 277

Answers (1)

MrSimple
MrSimple

Reputation: 599

You need to put a must_not behind the must. I tested this in my environment (except I used term instead of match) and it filtered the unwanted elements.

GET /_search
{
  "query": {
    "nested": {
      "path": "name",
      "query": {
        "bool": {
          "must": [
            { 
              "match" : {"name.first" : "Tom"}}
          ],
          "must_not": [
            { 
              "match" : {"status" : "married"}}
          ]
        }
      }
    }
  }
}

Upvotes: 1

Related Questions