我可以在基于 HTTP 的 JEST
客户端中通过 JSON
查询实现聚合
功能,但不能在 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 客户端的打印响应显示聚合结果。
在 elasticsearch
中使用 TCP 客户端
,可以通过 AggregationBuilder
进行聚合
。
当我尝试在 TCP
中实现 JSON 查询时,它没有返回聚合结果。
TCP 不支持通过查询字符串聚合但支持添加聚合选项有什么原因吗?
TCP Java 客户端示例代码:
已编辑
删除了 queryString 周围的 WrapperQueryBuilder
。
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
的主要文档中类,声明:
A Query builder which allows building a query given JSON string or binary data provided as input. This is useful when you want to use the Java Builder API but still have JSON query strings at hand that you want to combine with other query builders.
这里的关键字是单词query,即你发送给ES_search
端点的请求中名为query
的部分,即:
{
"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
关于elasticsearch - 通过 JSON 查询在 Java 客户端中聚合 - 没有 AggregationBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34451988/