Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregation Support for Spring Data Elastic Search

Elastic search has deprecated Facets and recommend to use Aggregations (http://www.elastic.co/guide/en/elasticsearch/reference/1.x/search-aggregations.html) .

Is Spring Data Elastic Search supports this currently ?

If Yes, is there any Samples available ?

like image 493
Sathish Kumar Thiyagarajan Avatar asked May 12 '15 07:05

Sathish Kumar Thiyagarajan


1 Answers

Yes aggregation is supported.

Example :

    @Test
    public void shouldReturnAggregatedResponseForGivenSearchQuery() {
    // given
    IndexQuery article1 = new ArticleEntityBuilder("1").title("article four").subject("computing").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex();
    IndexQuery article2 = new ArticleEntityBuilder("2").title("article three").subject("computing").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex();
    IndexQuery article3 = new ArticleEntityBuilder("3").title("article two").subject("computing").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(30).buildIndex();
    IndexQuery article4 = new ArticleEntityBuilder("4").title("article one").subject("accounting").addAuthor(RIZWAN_IDREES).addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(40).buildIndex();

    elasticsearchTemplate.index(article1);
    elasticsearchTemplate.index(article2);
    elasticsearchTemplate.index(article3);
    elasticsearchTemplate.index(article4);
    elasticsearchTemplate.refresh(ArticleEntity.class, true);

    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
    assertThat(aggregations, is(notNullValue()));
    assertThat(aggregations.asMap().get("subjects"), is(notNullValue()));
}

code is copied from ElasticsearchTemplateAggregationTests.java

like image 174
Mohsin Husen Avatar answered Nov 08 '22 01:11

Mohsin Husen