I have a Json query string:
"\"query\":{\"match_all\": {}},\"aggs\":{\"avg1\":{\"avg\":{\"field\":\"age\"} } }";
When query is executed via Jest Client
, aggregation values are available.
But when this query is converted into a Query Builder (WrapperQueryBuilder
) object, getting the following exception.
; nested: QueryParsingException[[st1index] [_na] query malformed, must start with start_object]; }{[ixJ-6RHNR5C6fC7HfJHqaw][st1index][4]: SearchParseException[[st1index][4]: from[-1],size[-1]: Parse Failure [Failed to parse source [{
"query" : {
"wrapper" : {
"query" : "InF1ZXJ5Ijp7Im1hdGNoX2FsbCI6IHt9fSwiYWdncyI6eyJhdmcxIjp7ImF2ZyI6eyJmaWVsZCI6ImFnZSJ9IH0gfQ=="
}
}
}]]]; nested: QueryParsingException[[st1index] [_na] query malformed, must start with start_object]; }]
How do i fix this?
Edit 1: Code analysis: Code analysis details added:
public static void main(String[] args) throws Exception
{
try{
//Jest client building
JestClientFactory factory = new JestClientFactory();
HttpClientConfig config = new HttpClientConfig.
Builder("http://localhost:9201")
.connTimeout(10000)
.readTimeout(10000)
.multiThreaded(true).build();
factory.setHttpClientConfig(config);
JestClient jestClient = factory.getObject();
String query ="{\"query\":{\"match_all\": {}},\"aggs\":{\"avg1\":{\"avg\":{\"field\":\"age\"} } }}";
String query2 ="{\"match_all\": {}},\"aggs\":{\"avg1\":{\"avg\":{\"field\":\"age\"} } }}";
WrapperQueryBuilder wrapQB = new WrapperQueryBuilder(query2);
SearchSourceBuilder ssb = new SearchSourceBuilder();
ssb.query(wrapQB);
//working code commented
// Search.Builder searchBuilder = new Search.Builder(query).addIndex("st1index").addType("st1type");
//code which needs to be fixed
Search.Builder searchBuilder = new
Search.Builder(ssb.toString()).addIndex("st1index").addType("st1type");
SearchResult result = jestClient.execute(searchBuilder.build());
System.out.println(result.getJsonString());
}
catch(Exception e)
{
System.out.println("inside exception block");
e.printStackTrace();
}
}
with String query and with commented SearchSourceBuilder, aggs results are displayed. But by using WrapperQueryBuilder , unable to retrieve aggs results
You're almost there, you're simply missing enclosing braces:
"{\"query\":{\"match_all\": {}},\"aggs\":{\"avg1\":{\"avg\":{\"field\":\"age\"}}}}";
^ ^
| |
this one... ...and this one
UPDATE
In the WrapperQueryBuilder
, you can only pass the content of the query
part, and not the aggregations
part. You need to add the aggregation part directly on the SearchSourceBuilder
like this:
SearchSourceBuilder ssb = new SearchSourceBuilder();
// add the query part
String query ="{\"match_all\": {}}";
WrapperQueryBuilder wrapQB = new WrapperQueryBuilder(query);
ssb.query(wrapQB);
// add the aggregation part
AvgBuilder avgAgg = AggregationBuilders.avg("avg1").field("age");
ssb.aggregation(avgAgg);