[[search-facets-terms-stats-facet]]
=== Terms Stats Facet

The `terms_stats` facet combines both the
<<search-facets-terms-facet,terms>> and
<<search-facets-statistical-facet,statistical>>
allowing to compute stats computed on a field, per term value driven by
another field. For example:

[source,js]
--------------------------------------------------
{
    "query" : {
        "match_all" : {  }
    },
    "facets" : {
        "tag_price_stats" : {
            "terms_stats" : {
                "key_field" : "tag",
                "value_field" : "price"
            }
        }
    }
}
--------------------------------------------------

The `size` parameter controls how many facet entries will be returned.
It defaults to `10`. Setting it to 0 will return all terms matching the
hits (be careful not to return too many results).

One can also set `shard_size` (in addition to `size`) which will determine
how many term entries will be requested from each shard. When dealing
with field with high cardinality (at least higher than the requested `size`)
The greater `shard_size` is - the more accurate the result will be (and the
more expensive the overall facet computation will be). `shard_size` is there
to enable you to increase accuracy yet still avoid returning too many
terms_stats entries back to the client.

Ordering is done by setting `order`, with possible values of `term`,
`reverse_term`, `count`, `reverse_count`, `total`, `reverse_total`,
`min`, `reverse_min`, `max`, `reverse_max`, `mean`, `reverse_mean`.
Defaults to `count`.

The value computed can also be a script, using the `value_script`
instead of `value_field`, in which case the `lang` can control its
language, and `params` allow to provide custom parameters (as in other
scripted components).

Note, the terms stats can work with multi valued key fields, or multi
valued value fields, but not when both are multi valued (as ordering is
not maintained).
