Search code examples
elasticsearchelastic-stack

Elasticsearch: Query to filter out specific documents based on field value and return count


I'm trying to compose a query in Elasticsearch that filters out documents with a specific field value, and also returns the number of documents that has been filtered out as an aggregation.

What I have so far is below, however, with my solution it seems that the documents are filtered out first, then after the filtering, the count is performed, which is making it always be 0.

{
   "query":{
      "bool":{
         "must_not":[
            {
               "terms":{
                  "gender":[
                     "male"
                  ]
               }
            }
         ]
      }
   },
   "aggs":{
      "removed_docs_count":{
         "filter":{
            "term":{
               "gender":"male"
            }
         }
      }
   }
}

Solution

  • You don't need a query block, just aggs will provide you expected results.

    {
       "aggs":{
          "removed_docs_count":{
             "filter":{
                "term":{
                   "gender":"male"
                }
             }
          }
       }
    }