1

It's possible build a query with aggregation (elasticsearch), using java-query-dsl?

1 Answer 1

3

ElasticSearch provides a client lib that helps you to build searches. You can find more about it here. Here's an example of how you can do it:

// 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);

which will produce something like:

GET customers/customer/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "range": {
            "age": {
              "gt": 25,
              "lt": 40
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "gender": {
      "terms": {
        "field": "gender",
        "size": 5
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.