我能够aggregation
通过JSON
基于HTTP的JEST
客户端中的查询来实现功能,但不能TCP
基于基于Java的客户端中。
通过JEST
客户端(基于HTTP REST),可以通过查询字符串实现聚合。
JEST示例代码:
JestClientFactory factory = new JestClientFactory();
HttpClientConfig httpClientConfig = new HttpClientConfig
.Builder("http://localhost:9201")
.build();
factory.setHttpClientConfig(httpClientConfig);
JestClient client = factory.getObject();
String queryString ="{\"query\":{\"match_all\": {}},\"aggs\":{\"avg1\":{\"avg\":{\"field\":\"age\"} } }}";
Search.Builder searchBuilder = new Search.Builder(queryString)
.addIndex("st1index")
.addType("st1type");
SearchResult response = client.execute(searchBuilder.build());
System.out.println(response.getJsonString());
client.shutdownClient();
JEST客户端的打印响应显示聚合结果。
使用TCP client
中elasticsearch
,aggregation
有可能通过AggregationBuilder
。
当我尝试在中实现JSON查询时 TCP
,它没有返回聚合结果。
TCP是否不支持通过查询字符串进行聚合但支持添加聚合选项的任何原因?
TCP Java客户端示例代码:
编辑已 删除WrapperQueryBuilder
queryString周围的内容。
Settings settings = ImmutableSettings.settingsBuilder()
.put("cluster.name", "javaEscluster")
.put("node.name", "arivu").build();
Client client = new TransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress("localhost", 9303));
String queryString ="{\"match_all\": {},\"aggs\":{\"avg1\":{\"avg\":{\"field\":\"age\"} } }}";
SearchResponse response = client.prepareSearch("st1index").setTypes("st1type").setQuery(queryString).execute().actionGet();
System.out.println("Getresponse-->" +"Index-->"+ response.toString());
//closing node
client.close();
System.out.println("completed");
此代码仅检索搜索结果和空的聚合结果数据。
编辑:
任何解释原因的参考资料都很好。
WrapperQueryBuilder
该类的主要文档中指出:
一个查询构建器,它允许在给定作为输入提供的JSON字符串或二进制数据的情况下构建查询。当您要使用Java Builder
API但仍要与其他查询构建器结合使用的JSON查询字符串时,此功能很有用。
这里的关键字是单词 query ,即在query
您发送到ES _search
端点的请求中命名的部分,即:
{
"sort": {
... <--- whatever sorting definition you have goes here
},
"_source": {
... <--- whatever source definition you have goes here
},
"query": {
... <--- this is the content you can use with WrapperQueryBuilder
},
"aggs": {
... <--- whatever aggs definition you have goes here
}
}
WrapperQueryBuilder
只会考虑您可以在该query
部分中找到的所有内容,因此您可以看到其中不包括聚合,聚合不在请求的另一个顶级部分中。
因此,在您提供的JSON查询字符串中,match_all
将仅考虑,因为这是允许显示在query
部分中的唯一有效令牌,而aggs:{...}
部分则没有。
"{\"match_all\": {},\"aggs\":{\"avg1\":{\"avg\":{\"field\":\"age\"} } }}"
^ ^
| |
this is valid this is NOT valid