Unable to execute query+aggs in same query string via SearchRequestBuilder


#1

hi
i am trying to execite and ealstic search query with aggrgates .. but seems like the "query" api don't allows to have "aggs" inside

My Java Code:
SearchRequestBuilder searchRequestBuilder = elasticsearchTemplate.getClient()
.prepareSearch(ElasticSearchConfig.AUDIENCE_INDEX_NAME);
searchRequestBuilder.setSearchType(SearchType.DFS_QUERY_THEN_FETCH);
searchRequestBuilder.setTypes(ElasticSearchConfig.AUDIENCE_DOC_TYPES);
searchRequestBuilder.setQuery(esQuery);
searchRequestBuilder.setQuery(esQuery);

    // searchRequestBuilder.execute().actionGet().getHits().getTotalHits();
    Filters agg = searchRequestBuilder.execute().actionGet().getAggregations()
            .get(AUDIENCE_AGGREGATE_IDENT);
    // sort services with most hits first
    Bucket maxBucket = agg.getBuckets().stream()
            .max((serviceA, serviceB) -> serviceA.getDocCount() < serviceB.getDocCount() ? -1
                    : serviceA.getDocCount() > serviceB.getDocCount() ? 1 : 0)
            .get();

My Query:
{
"query": {
"filtered": {
"query": {
"match_all": {
}
},
"filter": {
"ids": {
"values": ["1","2"]
}
}
}
},
"aggs": {
"audience": {
"filters": {
"filters": {
"deviceonline": { "term": {
"gender": "m"
} }
}
}
}
}
}

The Error it throws is "nested: QueryParsingException[[audience] No query registered for [query]]".

From stackoverflow comments i guess the SearchRequestBuilder is adding another "query":{...} around the complete search string and than complains to have two of them. Does that mean only "query" content ist allowed gere but no "aggs" - searchRequestBuilder.setQuery( ...ONLY "query" string here)
I can't remove the "query" because its needed on the same level as the "aggs" bot below. Btw i test the complete query against an es instance via the webfrontend https://www.found.no/play/#search - that worked (being converted to yml before)
Does that mean i have to find stgh like searchRequestBuilder.setAggregations(String) and call that wih only the "aggs" part of my query?
However i only find "strange" method signatures for setAggregations() . i don't know how to get my "aggs" filter expression converted into one of the required param types.


(system) #2