如何使用spring-data-elasticsearch中的聚合获取elasticsearch json响应?

时间:2015-12-27 17:38:50

标签: java elasticsearch spring-data-elasticsearch

我有以下内容: 我注意到在运行代码结束时,如果我打印出aggregations.asMap()。get(' subject'); 我正进入(状态: org.elasticsearch.search.aggregations.bucket.terms.StringTerms@6cff59fa

打印出来"聚合"给我:org.elasticsearch.search.aggregations.InternalAggregations@65cf321d

我真正想要的是整个字符串/ json响应,如果你要使用elasticsearch来获取聚合,通常会返回该响应。如何从聚合查询中获取原始响应?此外,有没有办法迭代和打印那些"包裹的"对象

https://github.com/spring-projects/spring-data-elasticsearch/blob/ab7e870d5f82f6c0de236048bd7001e8e7d2a680/src/test/java/org/springframework/data/elasticsearch/core/aggregation/ElasticsearchTemplateAggregationTests.java

@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
}

2 个答案:

答案 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获取聚合字段。