Aggregations

picturesafe-search supports aggregations, that can be used for facet searches.

The SearchAggregation instances for the requested fields are passed to the ElasticsearchService via SearchParameter and a list of corresponding ResultFacet instances is returned as part of the SearchResult:

SearchParameter searchParameter = SearchParameter.builder()
        .pageSize(20)
        .pageIndex(1)
        .sortOptions(SortOption.asc("id"))
        // Aggregate up to 10 facet items of the terms of field 'city'
        .aggregations(TermsAggregation.field("city").maxCount(10)) 
        .build();

SearchResult searchResult 
        = singleIndexElasticsearchService.search(expression, searchParameter);

for (ResultFacet resultFacet : searchResult.getFacets()) {
    // Name of facet, for example 'city'
    String facetName = resultFacet.getName();
    // Facet count for whole query, for example 35
    long facetCount = resultFacet.getCount();
    for (ResultFacetItem resultFacetItem : resultFacet.getFacetItems()) {
        // Facet item value, for example 'Hamburg'
        Object facetItemValue = resultFacetItem.getValue();
        // Facet item count, for example 21
        long facetItemCount = resultFacetItem.getCount();
    }
}

If you are not familiar with aggregations yet and don’t know which one to choose, or you simply want to rely on the predefined aggregation behavior of picturesafe-search, you can use the DefaultAggregation class:

DefaultAggregation.field("city")

Facet searches

The facets returned in the SearchResult can be used to refine the search.

Based on the example above, the following search limits the SearchResult for a specific city:

OperationExpression op = OperationExpression.and(expression,
        new ValueExpression("city", "Hamburg"));

searchResult = singleIndexElasticsearchService.search(op, searchParameter);

The original search Expression is combined with AND with the value of a ResultFacetItem and then searched again. In this example, the original SearchResult is refined to all documents containing the city ‘Hamburg’.

An aggregation/facet sample can be found here.