How can i use a annotation to do an aggragation li

2020-04-27 04:10发布

问题:

How can I use an annotation to do an aggragation like @Query(value = "{"query":""}") with spring-data-elasticsearch?

回答1:

You cannot do it with the @Query annotation whose only purpose is to send a query, not aggregations.

The only way to achieve this with Spring Data Elasticsearch is to leverage NativeSearchQueryBuilder and ElasticsearchTemplate:

SearchQuery searchQuery = new NativeSearchQueryBuilder()
    .withQuery(QueryBuilders.matchAll())
    .withSearchType(COUNT)
    .withIndices("your_index")
    .withTypes("your_type")
    .addAggregation(AggregationBuilders.terms("tags").field("tag"));

elasticsearchTemplate.queryForPage(searchQuery, YourEntity.class);