﻿---
title: Value count aggregation
description: A single-value metrics aggregation that counts the number of values that are extracted from the aggregated documents. These values can be extracted either...
url: https://www.elastic.co/elastic/docs-builder/docs/3028/reference/aggregations/search-aggregations-metrics-valuecount-aggregation
products:
  - Elasticsearch
---

# Value count aggregation
A `single-value` metrics aggregation that counts the number of values that are extracted from the aggregated documents. These values can be extracted either from specific fields in the documents, or be generated by a provided script. Typically, this aggregator will be used in conjunction with other single-value aggregations. For example, when computing the `avg` one might be interested in the number of values the average is computed over.
`value_count` does not de-duplicate values, so even if a field has duplicates each value will be counted individually.
```json

{
  "aggs" : {
    "types_count" : { "value_count" : { "field" : "type" } }
  }
}
```

Response:
```json
{
  ...
  "aggregations": {
    "types_count": {
      "value": 7
    }
  }
}
```

The name of the aggregation (`types_count` above) also serves as the key by which the aggregation result can be retrieved from the returned response.

## Script

If you need to count something more complex than the values in a single field you should run the aggregation on a [runtime field](https://docs-v3-preview.elastic.dev/elastic/docs-builder/docs/3028/manage-data/data-store/mapping/runtime-fields).
```json

{
  "size": 0,
  "runtime_mappings": {
    "tags": {
      "type": "keyword",
      "script": """
        emit(doc['type'].value);
        if (doc['promoted'].value) {
          emit('hot');
        }
      """
    }
  },
  "aggs": {
    "tags_count": {
      "value_count": {
        "field": "tags"
      }
    }
  }
}
```


## Histogram fields

When the `value_count` aggregation is computed on [histogram fields](https://www.elastic.co/elastic/docs-builder/docs/3028/reference/elasticsearch/mapping-reference/histogram), the result of the aggregation is the sum of all numbers in the `counts` array of the histogram.
For example, for the following index that stores pre-aggregated histograms with latency metrics for different networks:
```json

{
  "network.name" : "net-1",
  "latency_histo" : {
      "values" : [0.1, 0.2, 0.3, 0.4, 0.5],
      "counts" : [3, 7, 23, 12, 6] <1>
   }
}


{
  "network.name" : "net-2",
  "latency_histo" : {
      "values" :  [0.1, 0.2, 0.3, 0.4, 0.5],
      "counts" : [8, 17, 8, 7, 6] <1>
   }
}


{
  "aggs": {
    "total_requests": {
      "value_count": { "field": "latency_histo" }
    }
  }
}
```

Eventually, the aggregation will add all values for all histograms and return the following result:
```json
{
  ...
  "aggregations": {
    "total_requests": {
      "value": 97
    }
  }
}
```