user2689782
user2689782

Reputation: 757

Elasticsearch 5.x find documents where nested object does not exist

I have an index with a nested object. Mapping is like -

{
  "mappings": {
    "my_type": {
      "properties": {
        "group": {"type": "string"},
        "users": {
          "type": "nested", 
           "properties": {
                 "first": {"type": "string"},
                 "last": {"type": "string"}
           }
        }
      }
    }
  }
}

I need to find all documents which have no 'users'. I can see how to find only document which have users -

GET /my_index/my_type/_search
{
  "query": {
      "nested": {
          "path": "users",
             "query": {
                 "bool": {
                    "must": [
                     {
                      "exists": {
                           "field": "users"
                          }
                      }
                  ]
                 }
          }
       }
    }
 }

but I don't know how to do the reverse. Any pointers?

Upvotes: 0

Views: 491

Answers (1)

mickl
mickl

Reputation: 49945

You can use must_not as an outer boolean query combined with your nested one.

{
 "query": {
   "bool": {
     "must_not": [
       {
         "nested": {
           "path": "users",
           "query": {
             "bool": {
               "filter": {
                 "exists": {
                   "field": "users"
                 }
               }
             }
           }
         }
       }
     ]
   }
 }

}

Verified on 5.3.0

Upvotes: 1

Related Questions