class ElasticsearchHelper {

    public Terms getNestedAggregation(SearchResponse searchResponse, String nestedAggregationName, String subAggregationName)
    {
        // Retrieve the aggregations from the search response.
        Aggregations searchResponseAggregations = getAggregationsFromSearchResponse(searchResponse);

        // Retrieve the nested aggregation.
        Nested nestedAggregation = searchResponseAggregations.get(nestedAggregationName);

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

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

        // Retrieve the aggregations from the nested aggregation.
        Aggregations nestedAggregationAggregations = getAggregationsFromNestedAggregation(nestedAggregation, searchResponse);

        // Retrieve the sub-aggregation.
        Terms subAggregation = nestedAggregationAggregations.get(subAggregationName);

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

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

        return subAggregation;
    }

}