| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 | [[search-aggregations-metrics-valuecount-aggregation]]=== Value Count AggregationA `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 (or a script generates multipleidentical values for a single document), each value will be counted individually.[source,console]--------------------------------------------------POST /sales/_search?size=0{    "aggs" : {        "types_count" : { "value_count" : { "field" : "type" } }    }}--------------------------------------------------// TEST[setup:sales]Response:[source,console-result]--------------------------------------------------{    ...    "aggregations": {        "types_count": {            "value": 7        }    }}--------------------------------------------------// TESTRESPONSE[s/\.\.\./"took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits,/]The name of the aggregation (`types_count` above) also serves as the key by which the aggregation result can beretrieved from the returned response.==== ScriptCounting the values generated by a script:[source,console]--------------------------------------------------POST /sales/_search?size=0{    "aggs" : {        "type_count" : {            "value_count" : {                "script" : {                    "source" : "doc['type'].value"                }            }        }    }}--------------------------------------------------// TEST[setup:sales]This will interpret the `script` parameter as an `inline` script with the `painless` script language and no script parameters. To use a stored script use the following syntax:[source,console]--------------------------------------------------POST /sales/_search?size=0{    "aggs" : {        "types_count" : {            "value_count" : {                "script" : {                    "id": "my_script",                    "params" : {                        "field" : "type"                    }                }            }        }    }}--------------------------------------------------// TEST[setup:sales,stored_example_script]NOTE:: Because `value_count` is designed to work with any field it internally treats all values as simple bytes.Due to this implementation, if `_value` script variable is used to fetch a value instead of accessing the fielddirectly (e.g. a "value script"), the field value will be returned as a string instead of it's native format.
 |