I'm using spring-boot-elasticsearch for the first time. I've now figured out how to describe my serial difference pipeline query using elastics java api. This query, as you'll see below is rather large, and returns several buckets for each object as well as the serial difference between each bucket. The examples I see of search in a Spring Data Repository all seem to spell out the query's json body in a Query Annotation like this:
@Repository
public interface SonarMetricRepository extends ElasticsearchRepository<Article, String> {
@Query("{\"bool\": {\"must\": {\"match\": {\"authors.name\": \"?0\"}}, \"filter\": {\"term\": {\"tags\": \"?1\" }}}}")
Page<Article> findByAuthorsNameAndFilteredTagQuery(String name, String tag, Pageable pageable);
}
That seems elegant for basic CRUD operations but how can I put my query below into the repository object without needing to use @Query's raw query syntax? If you have a similar example of what a Model object built for a serial difference query result or any pipeline aggregation that would be even more helpful as well. Basically I want a search method in my repository like this
Page<Serial Difference Result Object> getCodeCoverageMetrics(String projectKey, Date start, Date end, String interval, int lag);
I should mention part of the reason I want to use this object is that I will have other CRUD query in here as well, AND I think it'll handle pagination for me, so that's appealing.
Here is my query which shows the serial difference between code coverage on sonar projects from a 1 week time period:
SerialDiffPipelineAggregationBuilder serialDiffPipelineAggregationBuilder =
PipelineAggregatorBuilders
.diff("Percent_Change", "avg_coverage")
.lag(1);
AvgAggregationBuilder averageCoverageAggregationBuilder = AggregationBuilders
.avg("avg_coverage")
.field("coverage");
AggregationBuilder coverageHistoryAggregationBuilder = AggregationBuilders
.dateHistogram("coverage_history")
.field("@timestamp")
.calendarInterval(DateHistogramInterval.WEEK)
.subAggregation(averageCoverageAggregationBuilder)
.subAggregation(serialDiffPipelineAggregationBuilder);
TermsAggregationBuilder sonarProjectKeyAggregationBuilder = AggregationBuilders
.terms("project_key")
.field("key.keyword")
.subAggregation(coverageHistoryAggregationBuilder);
BoolQueryBuilder searchQuery = new BoolQueryBuilder()
.filter(matchAllQuery())
.filter(matchPhraseQuery("name.keyword", "my-sample-sonar-project"))
.filter(rangeQuery("@timestamp")
.format("strict_date_optional_time")
.gte("2020-07-08T19:29:12.054Z")
.lte("2020-07-15T19:29:12.055Z"));
// Join query and aggregation together
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
.query(searchQuery)
.aggregation(sonarProjectKeyAggregationBuilder);
SearchRequest searchRequest = new SearchRequest("sonarmetrics").source(searchSourceBuilder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);