class ElasticsearchHelper {

    public Terms getAggregation(SearchResponse searchResponse, String aggregationName)
    {
        // Retrieve the aggregations from the search response.
        Aggregations aggregations = getAggregationsFromSearchResponse(searchResponse);

        // Retrieve the specified aggregation.
        Terms aggregation = aggregations.get(aggregationName);

        // Fail if retrieved aggregation is null.
        if (aggregation == null)
        {
            // Log the error along with the search response contents.
            LOGGER.error("Failed to retrieve \"{}\" aggregation from the search response. searchResponse={}", aggregationName,
                jsonHelper.objectToJson(searchResponse));

            // Throw an exception.
            throw new IllegalStateException("Invalid search result.");
        }

        return aggregation;
    }

}