0

I want to build the following ES query using BoolQueryBuilders and Aggregator, but I am unable to do that.

{
  "size": 0,
  "query": {
    "bool": {
      "should": {
        "bool": {
          "filter": [
            {
              "terms": {
                "country": [
                  "France",
                  "China"
                ]
              }
            },
            {
              "term": {
                "lang": "en"
              }
            }
          ]
        }
      }
    }
  },
  "aggs": {
    "group_by_country": {
      "terms": {
        "field": "country",
        "size": 0
      },
      "aggs": {
        "top_hits_country": {
          "top_hits": {
            "size": 1
          }
        }
      }
    }
  }
}

I am able to build this query without the aggregator, in the following manner -

BoolQueryBuilder innerEntityQueryBuilder = new BoolQueryBuilder();
        
BoolQueryBuilder queryBuilder = new BoolQueryBuilder()
                    .filter(QueryBuilders.termsQuery("country", countries)) 
                    .filter(QueryBuilders.termQuery("lang", "en")); 
innerEntityQueryBuilder.should(queryBuilder);

How do I add the aggregate part as well?

1 Answer 1

1

like this:

SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("index1");

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.size(0);

BoolQueryBuilder bqb = new BoolQueryBuilder()
        .filter(QueryBuilders.termsQuery("country", "France","China"))
        .filter(QueryBuilders.termQuery("lang", "en"));
searchSourceBuilder.query(bqb);


TermsAggregationBuilder group = AggregationBuilders
        .terms("group_by_country").field("country")
        .size(0);
TopHitsAggregationBuilder topHit = AggregationBuilders.topHits("top_hits_country").size(1);
group.subAggregation(topHit);

searchSourceBuilder.aggregation(group);

searchRequest.source(searchSourceBuilder);
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.