Using scripts with aggregation

Hi, I have a use case where the value of a field name signal can be 0, 1, or 2. I have to perform aggregation on this field but there are few records in the index without the field.

For the field not_exist, I need to assign the value 0 to it and then perform aggregation. How should I use script in this case.

Mapping is as follow:

  "product": {
    "mappings" : {
      "properties" : {
        "company_id" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
        "company_name" : {
          "type" : "text",
          "fields" : {
            "keyword" : {
              "type" : "keyword",
              "ignore_above" : 256
            }
          }
        },
      "signal" : {
          "type" : "long"
        },
}
}
}
}```

```POST product/_doc
{
			"company_id": 22,
			"company_name": "abc",
                        "signal": 0
}

POST product/_doc
{
			"company_id": 23,
			"company_name": "abcd",
                        "signal": 1
}

POST product/_doc
{
			"company_id": 24,
			"company_name": "ab",
                        "signal": 2
}

POST product/_doc
{
			"company_id": 25,
			"company_name": "abcde"
}```


Expected output:

```"buckets" : [
        {
          "key" : 0,
          "doc_count" : 2
        },
        {
          "key" : 1,
          "doc_count" : 1
        },
       {
          "key" : 2,
          "doc_count" : 1
        }
      ]```
POST product/_search
{
  "size": 0,
  "aggs": {
    "signal_agg": {
      "terms": {
        "script": {
          "source": "doc.containsKey('signal') ? doc['signal'].value : 0"
        }
      }
    }
  }
}

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