简体   繁体   中英

How to write elasticsearch query aggregation in java?

This is my code in Marvel Sense:

GET /sweet/cake/_search
{
  "query": {
    "bool": {
      "must": [
        {"term": {
          "code":"18"
        }}
      ]
    }
  },
  "size": 0,
  "aggs": {
    "group_by_state": {
      "terms": {
        "field": "id"
      }
    }
  }
}

And I want to write it in Java but I dont't know how.

You can find some examples in the official documentation for the Java client.

But in your case, you need to create one bool/must query using the QueryBuilders and one terms aggregation using the AggregationBuilders . It goes like this:

// build the query
BoolQueryBuilder query = QueryBuilders.boolFilter()
    .must(QueryBuilders.termFilter("code", "18"));

// build the terms sub-aggregation
TermsAggregation stateAgg = AggregationBuilders.terms("group_by_state")
    .field("id");

SearchResponse resp = client.prepareSearch("sweet")
        .setType("cake")
        .setQuery(query)
        .setSize(0)
        .addAggregation(stateAgg)
        .execute()
        .actionGet();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM