我有以下内容: 我注意到在运行代码结束时,如果我打印出aggregations.asMap()。get(' subject'); 我正进入(状态: org.elasticsearch.search.aggregations.bucket.terms.StringTerms@6cff59fa
打印出来"聚合"给我:org.elasticsearch.search.aggregations.InternalAggregations@65cf321d
我真正想要的是整个字符串/ json响应,如果你要使用elasticsearch来获取聚合,通常会返回该响应。如何从聚合查询中获取原始响应?此外,有没有办法迭代和打印那些"包裹的"对象
@Test
public void shouldReturnAggregatedResponseForGivenSearchQuery() {
// given
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.withSearchType(COUNT)
.withIndices("articles").withTypes("article")
.addAggregation(terms("subjects").field("subject"))
.build();
// when
Aggregations aggregations = elasticsearchTemplate.query(searchQuery, new ResultsExtractor<Aggregations>() {
@Override
public Aggregations extract(SearchResponse response) {
return response.getAggregations();
}
});
// then
System.out.println(aggregations); // gives me some cryptic InternalAggregations object, how do I get to the raw JSON normally returned by elasticsearch?
System.out.println(aggregations.asMap().get("subjects")); // gives me some StringTerms object I have no idea how to iterate over to get results
}
答案 0 :(得分:2)
您无法以这种方式获取原始JSON响应,因为Spring Data Elasticsearch将负责为您解析它,这就是重点。
如果您需要解析这些存储桶,您可以轻松地执行此操作:
...
StringTerms subjects = aggregations.asMap().get("subjects");
for (Terms.Bucket bucket : subjects.getBuckets()) {
String key = bucket.getKey();
long docCount = bucket.getDocCount();
// do something with the key and the doc count
}
如果你真的想要看到返回的JSON,你可以做的是使用序列化将解析后的Aggregations对象重写为JSON,但这不会真正有用:
InternalAggregations aggregations = ...;
XContentBuilder jsonBuilder = JsonXContent.contentBuilder();
aggregations.toXContent(jsonBuilder, ToXContent.EMPTY_PARAMS);
String rawJson = jsonBuilder.string();
答案 1 :(得分:-1)
将EsRequest的大小设置为零
获取Esresponse.toString()
将字符串转换为Json
从Json获取聚合字段。