I found the same question here. But this is not working in ES 6.2.4.
In old version, we can do this:
SearchRequestBuilder builder = client.prepareSearch(index);
QueryBuilder queryBuilder = getQueryBuilder(query);
builder.setQuery(queryBuilder); // set query
builder.setAggregations(agg.toString().getBytes()); // set aggregation
But in 6.2.4, we only have these 2 APIs:
How to make the "set aggregation" from JSON string work correctly?