Value count aggregation
The value_count metric is a single-value metric aggregation that counts the number of values extracted from the aggregated documents. These values can be extracted from specific fields in the documents or generated by a script. This aggregation is often paired with aggregations like avg to determine how many values contributed to a computed result.
The value_count aggregation does not deduplicate values. If a field contains duplicates or a script generates multiple identical values for a single document, each value is counted individually.
Parameters
The value_count aggregation takes the following parameters.
| Parameter | Data type | Description |
|---|---|---|
field | String | The field from which to count values. |
script | Object | A script that generates values to count. Can be used instead of or with field. |
missing | Number or String | The default value assigned to documents missing the target field. |
Example
The following example counts the number of documents that contain a taxful_total_price value in the e-commerce index:
GET /opensearch_dashboards_sample_data_ecommerce/_search
{
"size": 0,
"aggs": {
"number_of_values": {
"value_count": {
"field": "taxful_total_price"
}
}
}
}
The response shows that 4,675 documents contain values for the specified field:
{
...
"hits": {
"total": {
"value": 4675,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"aggregations": {
"number_of_values": {
"value": 4675
}
}
}
The aggregation name (number_of_values) also serves as the key for retrieving the aggregation result from the response.
Using a script
Instead of specifying a field, you can provide a script to generate values for counting. The following example uses an inline Painless script to count based on computed values:
GET /opensearch_dashboards_sample_data_ecommerce/_search
{
"size": 0,
"aggs": {
"type_count": {
"value_count": {
"script": {
"source": "doc['taxful_total_price'].value"
}
}
}
}
}
The response returns the count of script-generated values:
{
...
"hits": {
"total": {
"value": 4675,
"relation": "eq"
},
"max_score": null,
"hits": []
},
"aggregations": {
"type_count": {
"value": 4675
}
}
}
Using a stored script
To reuse a script across multiple queries, you can store it and reference it by ID. The following example uses a stored script that accepts a field name as a parameter:
GET /opensearch_dashboards_sample_data_ecommerce/_search
{
"size": 0,
"aggs": {
"type_count": {
"value_count": {
"script": {
"id": "my_value_count_script",
"params": {
"field": "taxful_total_price"
}
}
}
}
}
}
Because value_count internally represents all values as byte sequences, using the _value script variable to access field values returns the value as a string rather than its native format.