Each aggregation has a different purpose and should be processed differently once returned from the search engine, but you add the aggregation information to the search request in a similar way between all aggregations.
Instantiate and Construct the Aggregation
-
Use the
com.liferay.portal.search.aggregation.Aggregations
to instantiate the aggregation you’ll construct. For example,PercentilesAggregation percentilesAggregation = aggregations.percentiles("percentiles", Field.PRIORITY);
To discover what fields each aggregation must have (e.g.,
Sting name, String field
in the case of the abovePercentilesAggregation
), see theAggregations
interface. -
Build out the aggregation to get the desired response. This looks different for each aggregation type, but Elasticsearch’s documentation on the aggregation type explains it well (such as Percentiles Aggregations) combined with the setters in Liferay’s corresponding interface.
For example, use the
setPercentilesMethod(PercentilesMethod.HDR)
method to use the High Dynamic Range Histogram for calculating the percentiles.percentilesAggregation.setPercentilesMethod(PercentilesMethod.HDR);
Once the aggregation itself is in good shape, feed it to the search query.
Build the Search Query
-
Get an instance of
com.liferay.portal.search.searcher.SearchRequestBuilder
from theSearchRequestBuilderFactory
service:SearchRequestBuilder searchRequestBuilder = searchRequestBuilderFactory.builder();
-
Get a
com.liferay.portal.search.searcher.SearchRequest
instance from the builder, then add the aggregation to it and run itsbuild
method:SearchRequest searchRequest = searchRequestBuilder.addAggregation(percentilesAggregation).build();
Execute the Search Query
-
Perform a search using the
Searcher
service and theSearchRequest
to get acom.liferay.portal.search.searcher.SearchResponse
:SearchResponse searcher.search(searchRequest);
-
To satisfy the dependencies of the example code here, get a reference to
com.liferay.portal.search.searcher.SearchRequestBuilderFactory
andcom.liferay.portal.search.searcher.Searcher
:@Reference protected Searcher searcher; @Reference SearchRequestBuilderFactory searchRequestBuilderFactory;
Process the response
What you’ll do with the SearchResponse
returned by the searcher.search
call
depends on the type of aggregation and your specific use case. A separate
article will be written to demonstrate how to process the response.