Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pseudorandoom/285577a3a7b665014d35fce910f0346f to your computer and use it in GitHub Desktop.
Save pseudorandoom/285577a3a7b665014d35fce910f0346f to your computer and use it in GitHub Desktop.
Shows how to do aggregations in Elasticsearch via the Java api
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.search.builder.SearchSourceBuilder;
public class RestHighLevelClientAggregationExample {
private static final String INDEX = "your-es-index";
public static final String YOUR_INDEX_TYPE = "your-index-type";
public static final String HOST = "your-host";
public static final int PORT = 9200;
public static void main(String[] args) throws Exception {
RestClient restClient = RestClient.builder(new HttpHost(HOST, PORT, "http")).build();
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClient);
SearchRequest searchRequest = new SearchRequest(INDEX);
searchRequest.types(YOUR_INDEX_TYPE);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.aggregation(AggregationBuilders.sum("suma").field("numericField"));
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
// Brings only the result of the aggregation (optional)
searchSourceBuilder.size(0);
searchRequest.source(searchSourceBuilder);
final SearchResponse response = restHighLevelClient.search(searchRequest);
Sum suma = response.getAggregations().get("suma");
System.out.println("Response = " + suma.getValue());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment