How to aggregate nested fields with null values?

Hi,

I'm having trouble aggregating my nested data, maybe you can help.

I'll simplify the problem, I've a nested field that looks like:

PUT test/doc/_mapping 
{
  "properties": {
    "fields": {
            "type" : "nested",
            "properties" : {
              "name" : {
                "type" : "keyword"
              },
              "value" : {
                "type" : "long"
              }
            }
    }
  }
}

I created 3 documents:

PUT test/doc/1
{
  "fields" : {
    "name" : "aaa",
    "value" : 1
  }
}

PUT test/doc/2
{
  "fields" : [{
"name" : "aaa",
"value" : 1
  },
  {
"name" : "bbb",
"value" : 2
  }]
}

PUT test/doc/3
{
  "fields" : [
  {
"name" : "bbb",
"value" : 2
  }]
}

Now I want to group my data to get how many documents there are where name="bbb" group by each value.

For the above data I want to get:

2 – 2 documents

N/A – 1 document (the first document where bbb is missing)

The problem is with the null values, I cannot find a way to match the documents where "bbb" is null and put them in a N/A bucket.

What am I missing?

Find below the first comment where I wrote a query that match the values where "bbb" exist.

But I cannot find a way to match where "bbb" not exist, in the same query.

GET test/doc/_search
{
  "size": 0,
  "query": {
    "match_all": {}
  },
  "aggs": {
    "my_agg": {
      "nested": {
        "path": "fields"
      },
      "aggs": {
        "my_filter": {
          "filter": {
            "term": {
              "fields.name": "bbb"
            }
          },
          "aggs": {
            "my_term": {
              "terms": {
                "field": "fields.value"
              }
            }
          }
        }
      }
    }
  }
}

And the response is:

  "aggregations" : {
    "my_agg" : {
      "doc_count" : 4,
      "my_filter" : {
        "doc_count" : 2,
        "my_term" : {
          "doc_count_error_upper_bound" : 0,
          "sum_other_doc_count" : 0,
          "buckets" : [
            {
              "key" : 2,
              "doc_count" : 2
            }
          ]
        }
      }
    }
  }

I want to get also:

"key" : 0 (for N/A)
"doc_count" : 1

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.