DEV Community

Rajasekaran Palraj
Rajasekaran Palraj

Posted on

Handle Null in Elasticsearch Aggrgation

Sample Data

{"system": "aaa","ip":"0.0.0.1"},
{"system": "bbb","ip":"0.0.0.2"},
{"system": null,"ip":"0.0.0.3"},
{"ip":"0.0.0.4"}

Basic aggregation query

{
"aggs" : {
"myAggrs" : {
"terms" : { "field" : "system" }
}
}

Output for above:

{
"key": "aaa",
"doc_count": 1
},
{
"key": "bbb",
"doc_count": 1
}

It ignores whether the field is null or if it's missing

The expected result is

{
"key": "aaa",
"doc_count": 1
},
{
"key": "bbb",
"doc_count": 1
},
{
"key": null,
"doc_count": 2
}

To solve this, we have to change the query like this,
{
"aggs" : {
"myAggrs" : {
"terms" : { "field" : "system" },
"missing" : "NULL"
}
}

We will get below
{
"key": "aaa",
"doc_count": 1
},
{
"key": "bbb",
"doc_count": 1
},
{
"key": "NULL",
"doc_count": 2
}

Top comments (0)