2

While exploring aggregation in elasticsearch I found out that aggregation functionality can be implemented via JSON query in HTTP based JEST client but not in TCP based Java client.

I am using Jest Client and implemented aggregation through query String that works fine. But I feel it gets quiet cumbersome as the filters increase. I want to know if there is a way to implement aggregations other than using JSON query in JEST client (Something like aggregation builders in TCP client) and how do we implement it?

Machavity
  • 30,841
  • 27
  • 92
  • 100

2 Answers2

0

This was my solution to implement aggregations, don't forget to add the query first.

org.elasticsearch.search.builder.SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

TermsAggregationBuilder termsAggregationBuilder =
            AggregationBuilders.terms(fieldName).field("keyword");
termsAggregationBuilder.minDocCount(minDocCount);
termsAggregationBuilder.size(size);
searchRequestBuilder.aggregation(termsAggregationBuilder);

Search search = new io.searchbox.core.Search.Builder(searchSourceBuilder.toString())
     .addIndex(indexNameBuilder.getIndexName(searchContext.getCompanyId()))
     .build();

SearchResult result = jestConnectionManager.getClient().execute(search);
jkamcc
  • 361
  • 2
  • 3
0

Here's what I landed on:

SearchSourceBuilder searchBuilder = SearchSourceBuilder
     .searchSource()
     .size(0)
     .query(QueryBuilders.termQuery("field", "my value"))
     .aggregation(
          AggregationBuilders
              .sum("number_field_sum")
              .field("number_field")
     );
Search search = new Search.Builder(searchBuilder.toString())
     .addIndex("my-index")
     .build();
SearchResult result = jestClient.execute(search);

This is largely the same as what you came up with, but I put the query into the SearchSourceBuilder and I simplified the example a bit.

Sean Connolly
  • 5,692
  • 7
  • 37
  • 74