[Elasticsearch 5.4.x] Return additional data when using aggregations?


#1

Hi,

I am currently using the bucket aggregation functionality in Elastic and it's working fine, but wanted to know if there is a way to return additional data dynamically as part of the aggregation results.

I have this json

"from": 0,
"size": 9,
"aggs": {
   "group_by_work_location": {
       "terms": {
          "field": "work_location.keyword"
      }
   }
}

It returns a response like:

  "aggregations": {
     "group_by_work_location": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
            {
                "key": "Chicago, IL",
                "doc_count": 2
            }
        ]
    }
}

Based on the above, is there a way to return an additional field/key dynamically within the bucket array? I have a field in the data called "location_id". I would like to return this field alongside the "key" and "doc_count". Is there a way to do this?


(Luiz Santos) #2

Hi @west415,

I think a sub-aggregation can help you:

POST location/doc/1
{
  "work_location": "Chicago",
  "location_id": 123
}

POST location/doc/2
{
  "work_location": "New York",
  "location_id": 321
}

GET location/_search
{
  "size": 0,
  "aggs": {
    "group_by_work_location": {
      "terms": {
        "field": "work_location.keyword",
        "size": 10
      },
      "aggs": {
        "location_id": {
          "terms": {
            "field": "location_id",
            "size": 10
          }
        }
      }
    }
  }
} 

Result:

{
  "took": 9,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 0,
    "hits": []
  },
  "aggregations": {
    "group_by_work_location": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "Chicago",
          "doc_count": 1,
          "location_id": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
              {
                "key": 123,
                "doc_count": 1
              }
            ]
          }
        },
        {
          "key": "New York",
          "doc_count": 1,
          "location_id": {
            "doc_count_error_upper_bound": 0,
            "sum_other_doc_count": 0,
            "buckets": [
              {
                "key": 321,
                "doc_count": 1
              }
            ]
          }
        }
      ]
    }
  }
}

Best,
LG


#3

Thanks, @luiz.santos, I just tried it and it works fine. Thanks for the tip.


(system) #4

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