热门命中Jest SearchResult中的聚合支持

时间:2017-03-17 07:15:01

标签: java elasticsearch elastic-stack

我使用以下函数进行聚合查询:

private TermsBuilder getAggregations(String[] outputFields) {

        TermsBuilder topLevelAggr = AggregationBuilders.terms("level1").field("field1").size(0);
        TermsBuilder aggr2 = AggregationBuilders.terms("level2").field("field2").size(0);
        TermsBuilder aggr3 = AggregationBuilders.terms("level3").field("field3").size(0);
        TermsBuilder aggr4 = AggregationBuilders.terms("level4").field("field4").size(0);
        TopHitsBuilder topHitsBuilder = AggregationBuilders.topHits("doc").setSize(1).addSort("fieldValue", SortOrder.DESC);

        aggr4.subAggregation(topHitsBuilder);
        aggr3.subAggregation(aggr4);
        aggr2.subAggregation(aggr3);
        topLevelAggr.subAggregation(aggr2);
        topHitsBuilder.setFetchSource(outputFields, new String[]{});

        return topLevelAggr;
    }

我从此代码中获取了正确的聚合查询,但在执行查询后,我无法提取top_hits聚合结果。我在用 获取查询结果的io.searchbox.core.SearchResult类。在本课程中,我无法找到对Top_Hits聚合的任何支持。

请帮忙。感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用热门hits aggregation java API

这是来自elasticsearch docs的一个例子:

// sr is here your SearchResponse object
Terms agg = sr.getAggregations().get("agg");

// For each entry
for (Terms.Bucket entry : agg.getBuckets()) {
    String key = entry.getKey();                    // bucket key
    long docCount = entry.getDocCount();            // Doc count
    logger.info("key [{}], doc_count [{}]", key, docCount);

    // We ask for top_hits for each bucket
    TopHits topHits = entry.getAggregations().get("top");
    for (SearchHit hit : topHits.getHits().getHits()) {
        logger.info(" -> id [{}], _source [{}]", hit.getId(), hit.getSourceAsString());
    }
}