Making aggregations in two different types and return it grouped in Elasticsearch

Having this mapping with two types, items_one and items_two:

    curl -XPUT 'localhost:9200/tester?pretty=true' -d '{
      "mappings": {
          "items_one": {
             "properties" : {
               "type" : {"type": "string",
                         "index": "not_analyzed"}
            }},
          "items_two": {
             "properties" : {
               "other_type" : { "type": "string",
                         "index": "not_analyzed"}
    }}}}'

I put two items on items_one:

    curl -XPUT 'localhost:9200/tester/items_one/1?pretty=true' -d '{
        "type": "Bank transfer"
    }'
    
    curl -XPUT 'localhost:9200/tester/items_one/2?pretty=true' -d '{
        "type": "PayPal"
    }'

... and another two in items_two:

    curl -XPUT 'localhost:9200/tester/items_two/1?pretty=true' -d '{
        "other_type": "Cash"
    }'
    
    curl -XPUT 'localhost:9200/tester/items_two/2?pretty=true' -d '{
        "other_type": "No pay"
    }'

How can I make the aggregations in two different fields and return it grouped?

I know I can get it from one field doing:

    curl -XGET 'localhost:9200/tester/_search?pretty=true' -d '{
        "size": 0,
        "aggs": {
            "paying_types": {
                "terms": {
                    "field": "type"
                }
            }
        }
    }'

But I cant make it "multi-field" making something like this (which is not working):

    curl -XGET 'localhost:9200/tester/_search?pretty=true' -d '{
        "size": 0,
        "aggs": {
            "paying_types": {
                "terms": {
                    "field": ["type", "other_type"]
                }
            }
        }
    }'

My desired output should be:

      "aggregations" : {
        "paying_types" : {
          "doc_count_error_upper_bound" : 0,
          "sum_other_doc_count" : 0,
          "buckets" : [ {
            "key" : "Bank transfer",
            "doc_count" : 1
          }, {
            "key" : "PayPal",
            "doc_count" : 1
          }, {
            "key" : "Cash",
            "doc_count" : 1
          }, {
            "key" : "No pay",
            "doc_count" : 1
          } ]
        }
      }
    }

Thanks in advance

Finally solved it. A script will do the trick:

curl -XGET 'localhost:9200/tester/_search?pretty=true' -d '{
    "size": 0,
    "aggs": {
        "paying_types": {
            "terms": {
                 "script": "doc['type'].values + doc['other_type'].values"
            }
        }
    }
}'
1 Like