我有一个Json查询字符串:
"\"query\":{\"match_all\": {}},\"aggs\":{\"avg1\":{\"avg\":{\"field\":\"age\"} } }";
通过Jest Client
执行查询时,可以使用聚合值。
但是当此查询转换为查询生成器(WrapperQueryBuilder
)对象时,会出现以下异常。
; 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]; }]
我该如何解决这个问题?
编辑1:代码分析: 添加了代码分析详细信息:
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();
}
}
使用String查询并使用注释的SearchSourceBuilder显示aggs结果。但是通过使用WrapperQueryBuilder,无法检索aggs结果
答案 0 :(得分:1)
你几乎就在那里,你只是缺少括号:
"{\"query\":{\"match_all\": {}},\"aggs\":{\"avg1\":{\"avg\":{\"field\":\"age\"}}}}";
^ ^
| |
this one... ...and this one
<强>更新强>
在WrapperQueryBuilder
中,您只能传递query
部分的内容,而不能传递aggregations
部分的内容。您需要直接在SearchSourceBuilder
上添加聚合部分,如下所示:
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);