[[java-aggs-metrics-cardinality]]
==== Cardinality Aggregation

Here is how you can use
{ref}/search-aggregations-metrics-cardinality-aggregation.html[Cardinality Aggregation]
with Java API.


===== Prepare aggregation request

Here is an example on how to create the aggregation request:

[source,java]
--------------------------------------------------
MetricsAggregationBuilder aggregation =
        AggregationBuilders
                .cardinality("agg")
                .field("tags");
--------------------------------------------------


===== Use aggregation response

Import Aggregation definition classes:

[source,java]
--------------------------------------------------
import org.elasticsearch.search.aggregations.metrics.cardinality.Cardinality;
--------------------------------------------------

[source,java]
--------------------------------------------------
// sr is here your SearchResponse object
Cardinality agg = sr.getAggregations().get("agg");
long value = agg.getValue();
--------------------------------------------------


