Statistical Aggregations

Support for GroupBy and Stats aggregations were introduced in 7.0.

Cardinality Aggregations extend Liferay DXP’s metrics aggregation capabilities, providing an approximate (i.e., statistical) count of distinct values returned by a search query. For example, you could compute a count of distinct values of the tag field. Refer to the Elasticsearch documentation for more details.

While this functionality was available in the past directly in the portal kernel code, it’s been extracted and re-implemented in StatsRequest and StatsResponse, both introduced in the module to avoid modifying portal-kernel. StatsRequest provides the same statistical features that the legacy does, and adds the new cardinality option.


The StatsRequest Provides a map of field names and the metric aggregations that are to be computed for each field.

  1. Get a reference to

    SearchRequestBuilderFactory searchRequestBuilderFactory;
  2. Get an instance of

    SearchRequestBuilder searchRequestBuilder = searchRequestBuilderFactory.builder();
  3. Get a instance from the builder:

    SearchRequest searchRequest =;
  4. Get a reference to

    StatsRequestBuilderFactory statsRequestBuilderFactory;
  5. Get a instance and build with the desired metrics:

    StatsRequestBuilder statsRequestBuilder = 
    StatsRequest statsRequest = statsRequestBuilder
  6. Set StatsRequest on the SearchRequest:

  7. Get a reference to

    protected Searcher searcher;
  8. Perform a search using Searcher and SearchRequest to get


Click here to see an example from Liferay’s codebase


The stats response contains the metrics aggregations computed by the search engine for a given field.

  1. Get the map containing the metrics aggregations computed by the search engine:

    Map<String, StatsResponse> map = searchResponse.getStatsResponseMap();
  2. Get the StatsResponse for a given field:

    StatsResponse statsResponse = map.get(field);
  3. Get the desired metric, for example cardinality:


Click here to see an example from Liferay’s codebase

Using the Legacy Stats Object

The legacy object continues to be fully supported:

  1. Create a Stats instance with the desired metrics:

    Stats stats = new Stats() {
  2. Set Stats on the SearchContext:

    searchRequestBuilder.withSearchContext(searchContext -> searchContext.addStats(stats));

Click here to see an example from Liferay’s codebase

External References


Search Engine Connector Support

  • Elasticsearch 6: Yes
  • Solr 7: Yes

New/Related APIs

These are the relevant APIs for building Statistics Aggregations:

API (FQCN)Provided by Artifact statsRequests)

Deprecated APIs

  • SearchSearchRequest#getStats()
  • SearchSearchRequest#setStats(Map<String, Stats> stats)
« Creating AggregationsModel Entity Indexing Framework »
¿Fue útil este artículo?
Usuarios a los que les pareció útil: 0 de 0