# Elasticsearch JAVA API Aggregations casting error

**URL:** <https://discuss.elastic.co/t/elasticsearch-java-api-aggregations-casting-error/142009>\
**Category:** Elasticsearch\
**Created:** [July 28, 2018, 3:26am UTC](https://discuss.elastic.co/t/elasticsearch-java-api-aggregations-casting-error/142009 "2018-07-28T03:26:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![James\_Drinkard](https://avatars.discourse-cdn.com/v4/letter/j/9fc348/32.png) [@James\_Drinkard](https://discuss.elastic.co/u/James_Drinkard)\
**Post date:** [July 28, 2018, 3:26am UTC](https://discuss.elastic.co/t/elasticsearch-java-api-aggregations-casting-error/142009/1 "2018-07-28T03:26:50Z")

</div>

I had a task to create a nested AggregationBuilder with two levels with Elasticsearch 5.6. The query was similar to:  
GET \_data/\_search  
{  
"aggs":{  
"nestedAttributes":{  
"nested": {  
"path": "ATTRIBUTES": {  
},  
"aggs":{  
"filteredAttributes":{  
"term": {  
"ATTRIBUTES.TYPE": "AUTHORIZATIONS"  
},  
"aggs":{  
"descriptions":{  
"terms": {  
"field": "ATTRIBUTES.DESC",  
"size": 2  
}  
etc... closing braces  
The Java code was something like this:  
setAggregations(SearchRequestBuilder builder) {  
builder.AddAggregation( etc...

.subAggregation(AggregationsBuilders.nested("nestedPath", "ATTRIBUTES")  
.subAggregation(AggregationsBuilders.filter("filterName", QueryBuilders.boolQuery().must(QueryBuilders.termQuery("ATTRIBUTES.TYPE", "AUTHORIZATIONS")))  
.subAggregations("AggregationsBuilders.terms("attributesTerms").field("ATTRIBUTES.DESC")  
.size(1000000000)));

This code worked, but it was not testable, so I had to break it out into a method. The problem is I keep getting class cast errors trying to call it from within my code and I'm not sure what the correct types are?

Basically it's  
.subAggregations(getAttributes())  
.subAggregations( etc...

My method:  
private AggregationBuilder getAttributes() {  
//same AggregationBuilders code as above but with a return statement etc...  
return AggregationBuilder;  
}

I've tried to return a Builder, AggregationBuilder, but while it compiles I get a runtime class cast exception error each time. What type of object do I need to return to get this to run?

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [August 25, 2018, 3:37am UTC](https://discuss.elastic.co/t/elasticsearch-java-api-aggregations-casting-error/142009/2 "2018-08-25T03:37:17Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
