Percentage Calculation in Elasticsearch Aggregations

Hi everyone,

I'm looking for the best way to calculate percentages when working with aggregated data in Elasticsearch.

For example, suppose an index contains 10,000 documents, and 1,500 of them belong to a particular category. I want to calculate what percentage of all documents belongs to that category.

The basic formula is:

Percentage = (Category Document Count / Total Document Count) × 100

In this example, the result would be 15%.

I understand that Elasticsearch aggregations can group documents and return document counts, but I'm interested in the best approach for calculating and displaying the percentage, especially when working with multiple categories in Kibana.

Would a bucket script aggregation be suitable, or would it be better to calculate the percentage in the application or visualization layer?

Thanks in advance for any suggestions!

Hi @Oliver_Finsch
Welcome to the community!
What version of the stack are you using?

You could probably us ESQL something like this which is probably easier....

FROM traces-generic.otel-default
| STATS service_count = COUNT() BY service.name
| INLINE STATS total_count = SUM(service_count)
| EVAL pct = TO_DOUBLE(service_count) / total_count * 100.0
| KEEP service.name, service_count, total_count, pct
| SORT pct DESC
service.name service_count total_count pct
frontend 9,012 27,841 32.37
frontend-proxy 4,153 27,841 14.917
product-catalog 4,132 27,841 14.841
load-generator 3,749 27,841 13.466
checkout 1,528 27,841 5.488
...