如何使用高级Java客户端将具有同一级别的多个聚合的以下dsl查询转换为Java api?
{
"size": 0,
"aggs": {
"by_time": {
"max": {
"field": "updated_ts"
}
},
"by_question": {
"value_count": {
"field": "questions.question.keyword"
}
},
"by_score": {
"filter": {
"term": {
"score": 100
}
}
}
}
}
答案 0 :(得分:0)
嗨,如果您使用的是ES 6.8版或更低版本,请尝试使用此代码
MaxAggregationBuilder by_time = AggregationBuilders
.max("by_time")
.field("updated_ts");
ValueCountAggregationBuilder by_question = AggregationBuilders
.count("by_question")
.field("questions.question.keyword");
ValueCountAggregationBuilder by_view = AggregationBuilders
.count("by_view")
.field("questions.viewStats.name.keyword");
FilterAggregationBuilder by_score = AggregationBuilders
.filter("by_score", QueryBuilders.termQuery("score",100));
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//Setting aggregation to search request
sourceBuilder.aggregation(by_time);
sourceBuilder.aggregation(by_question);
sourceBuilder.aggregation(by_view);
sourceBuilder.aggregation(by_score);
//To avoid fetching docs
sourceBuilder.size(0);
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(MODEL_INDEX_NAME);
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//For getting result from aggregations
//Refer: https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/_structuring_aggregations.html
Max byTimeAggregationResult = searchResponse.getAggregations().get("by_time");
double byTimeMaxValue = byTimeAggregationResult.getValue();
ValueCount byQuestionAggregationResult = searchResponse.getAggregations().get("by_question");
long byQuestionCount = byQuestionAggregationResult.getValue();
ValueCount byViewAggregationResult = searchResponse.getAggregations().get("by_view");
long byViewCount = byViewAggregationResult.getValue();
Filter byScoreAggregationResult = searchResponse.getAggregations().get("by_score");
long byScoreDocCount = byScoreAggregationResult.getDocCount();
System.out.println("byTimeMaxValue: "+byTimeMaxValue);
System.out.println("byQuestionCount: "+byQuestionCount);
System.out.println("byViewCount: "+byViewCount);
System.out.println("byScoreDocCount: "+byScoreDocCount);