# How to merge aggregation bucket in Elasticsearch?

**URL:** https://discuss.elastic.co/t/how-to-merge-aggregation-bucket-in-elasticsearch/290230
**Category:** Elasticsearch
**Created:** [November 26, 2021, 4:33am UTC](https://discuss.elastic.co/t/how-to-merge-aggregation-bucket-in-elasticsearch/290230 "2021-11-26T04:33:56Z")
**Posts on this page:** 9
**Page:** 1

<div class="post-metadata">

### Author: ![hyun](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/hyun/32/97630_2.png) [@hyun](https://discuss.elastic.co/u/hyun)
#### Post date: [November 26, 2021, 4:33am UTC](https://discuss.elastic.co/t/how-to-merge-aggregation-bucket-in-elasticsearch/290230/1 "2021-11-26T04:33:56Z")

</div>

**Query**

```auto
GET /_search
{
  "size" : 0,
  "query" : {
    "ids" : {
      "types" : [],
      "values" : ["someId1", "someId2", "someId3" ...]
    }
  },
  "aggregations" : {
    "how_to_merge" : {
      "terms" : {
        "field" : "country",
        "size" : 50
      }
    }
  }
}

```

**Result**

```auto
{
   ...
   "aggregations": {
      "how_to_merge": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "KR",
               "doc_count": 90
            },
            {
               "key": "JP",
               "doc_count": 83
            },
            {
               "key": "US",
               "doc_count": 50
            },
            {
               "key": "BE",
               "doc_count": 9
            }
         ]
      }
   }
}

```

I want to merge "KR" and "JP" and "US"

And change key name to "NEW\_RESULT"

So result must like this:

```auto
{
   ...
   "aggregations": {
      "how_to_merge": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": "NEW_RESULT",
               "doc_count": 223
            },
            {
               "key": "BE",
               "doc_count": 9
            }
         ]
      }
   }
}

```

Is it possible in Elasticsearch query?

I cannot use a client-side solution since there are too many entities and retrieving all of them and merging would be probably too slow for my application.

Thanks for your help and comments!

---

<div class="post-metadata">

### Author: ![casterQ](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/casterq/32/93257_2.png) [@casterQ](https://discuss.elastic.co/u/casterQ)
#### Post date: [November 26, 2021, 10:35am UTC](https://discuss.elastic.co/t/how-to-merge-aggregation-bucket-in-elasticsearch/290230/2 "2021-11-26T10:35:09Z")

</div>

```auto
POST caster2/_search
{
  "size": 0,
  "aggs": {
    "groupbyk": {
      "adjacency_matrix": {
        "filters": {
          "group1": {
            "terms": {
              "k1": [
                "a",
                "b"
              ]
            }
          },
          "group2": {
            "terms": {
              "k1": [
                "c"
              ]
            }
          }
        }
      }
    }
  }
}

```

---

<div class="post-metadata">

### Author: ![casterQ](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/casterq/32/93257_2.png) [@casterQ](https://discuss.elastic.co/u/casterQ)
#### Post date: [November 26, 2021, 10:35am UTC](https://discuss.elastic.co/t/how-to-merge-aggregation-bucket-in-elasticsearch/290230/3 "2021-11-26T10:35:47Z")

</div>

@hyun this can work

---

<div class="post-metadata">

### Author: ![hyun](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/hyun/32/97630_2.png) [@hyun](https://discuss.elastic.co/u/hyun)
#### Post date: [November 29, 2021, 6:07am UTC](https://discuss.elastic.co/t/how-to-merge-aggregation-bucket-in-elasticsearch/290230/4 "2021-11-29T06:07:21Z")

</div>

@casterQ I don't understand the grammar.  
What is groupbyk and adjacency\_matrix?

Error message like:  
Could not find aggregator type [adjacency\_matrix] in [groupbyk]

---

<div class="post-metadata">

### Author: ![Mark\_Harwood](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mark_harwood/32/10538_2.png) [@Mark\_Harwood](https://discuss.elastic.co/u/Mark_Harwood)
#### Post date: [November 29, 2021, 11:24am UTC](https://discuss.elastic.co/t/how-to-merge-aggregation-bucket-in-elasticsearch/290230/5 "2021-11-29T11:24:16Z")

</div>

Scripts can be used to tweak values from the index. Here's an example

```auto
DELETE test
PUT test 
{
  "mappings": {
    "properties": {
      "country":{
        "type": "keyword"
      }
    }
  }
}

POST test/_doc/1
{"country" : "US"}
POST test/_doc/2
{"country" : "JP"}
POST test/_doc/3
{"country" : "KR"}
POST test/_doc/4
{"country" : "Other1"}
POST test/_doc/5
{"country" : "Other2"}
GET test/_search 
{
  "size":0,
  "aggs": {
    "countries": {
      "terms": {
        "script": {
          "params": {"synonyms":{
            "KR": "NewResult",
            "US": "NewResult",
            "JP": "NewResult"
          }},
          "source": """
          def syn = params['synonyms'][doc['country'].value];
          if (syn !=null) {return syn;} else{ return doc['country'].value;}
          """
        }
      }
    }
  }
}

```

---

<div class="post-metadata">

### Author: ![hyun](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/hyun/32/97630_2.png) [@hyun](https://discuss.elastic.co/u/hyun)
#### Post date: [November 30, 2021, 1:28am UTC](https://discuss.elastic.co/t/how-to-merge-aggregation-bucket-in-elasticsearch/290230/6 "2021-11-30T01:28:01Z")

</div>

@Mark_Harwood Thanks for your answer!

I am using version 2.2  
So I have to use inline script with groovy

I tried this query

```auto
"aggs": {
    "countries": {
      "terms": {
        "script": {
          "params": {"synonyms":{
            "KR": "NewResult",
            "US": "NewResult",
            "JP": "NewResult"
          }},
          "inline": "def syn = params['synonyms'][doc['country'].value]; if (syn != null) {return syn;} else {return doc['country'].value;};"
        }
      }
    }
  }

```

Then Error Like This:

```auto
"reason": {
               "type": "script_exception",
               "reason": "failed to run inline script [def syn = params['synonyms'][doc['country'].value]; if (syn != null) {return syn;} else {return doc['country'].value;};] using lang [groovy]",
               "caused_by": {
                  "type": "missing_property_exception",
                  "reason": "No such property: params for class: e82d610ed84d9787d1d68c886deeb38bf8cb319e"
               }
            }

```

If don't find the value in params, there's an error.  
How can I get the null value back if I don't find the value in params?

---

<div class="post-metadata">

### Author: ![Mark\_Harwood](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/mark_harwood/32/10538_2.png) [@Mark\_Harwood](https://discuss.elastic.co/u/Mark_Harwood)
#### Post date: [November 30, 2021, 7:34am UTC](https://discuss.elastic.co/t/how-to-merge-aggregation-bucket-in-elasticsearch/290230/7 "2021-11-30T07:34:08Z")

</div>

I’ve no idea I’m afraid because I don’t have 2.2/groovy. Try removing the params and hard coding the list of values in the script as “if == kr” type statements.  
Even better - upgrade. Later versions have:

- less bugs
- better supported  
• no serious security vulnerabilities like those found in older versions running groovy.

---

<div class="post-metadata">

### Author: ![warkolm](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/warkolm/32/39224_2.png) [@warkolm](https://discuss.elastic.co/u/warkolm)
#### Post date: [November 30, 2021, 9:04am UTC](https://discuss.elastic.co/t/how-to-merge-aggregation-bucket-in-elasticsearch/290230/8 "2021-11-30T09:04:53Z")

</div>

2.2 is very well past [EOL](https://www.elastic.co/support/eol) and no longer supported. You need to upgrade.

---

<div class="post-metadata">

### Author: ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)
#### Post date: [December 28, 2021, 9:05am UTC](https://discuss.elastic.co/t/how-to-merge-aggregation-bucket-in-elasticsearch/290230/9 "2021-12-28T09:05:03Z")

</div>

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