是否可以使用java-query-dsl构建具有聚合(elasticsearch)的查询?
答案 0 :(得分:1)
ElasticSearch提供了一个客户端库,可帮助您构建搜索。您可以找到有关here的更多信息。 这是一个如何做的例子:
// build the client
HttpHost host = new HttpHost("localhost", 9200, "http");
RestHighLevelClient client = new RestHighLevelClient(RestClient
.builder(new HttpHost[]{host}));
// build the search (set the conditions here)
BoolQueryBuilder boolQueryBuilder = boolQuery();
boolQueryBuilder.must(QueryBuilders.rangeQuery("age")
.from(25)
.to(40));
// build the aggregations (set the aggregations here)
TermsAggregationBuilder groupByGender = AggregationBuilders.terms("gender")
.field("gender")
.size(5);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(boolQueryBuilder);
sourceBuilder.aggregation(groupByGender);
// create and execute the search request
SearchRequest request = new SearchRequest()
.indices("customers")
.types("customer")
.allowPartialSearchResults(false)
.source(sourceBuilder)
.requestCache(true);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
这将产生类似的内容:
GET customers/customer/_search
{
"query": {
"bool": {
"must": [
{
"range": {
"age": {
"gt": 25,
"lt": 40
}
}
}
]
}
},
"aggs": {
"gender": {
"terms": {
"field": "gender",
"size": 5
}
}
}
}