Elasticsearch java api field extracting

I am trying to retrieve some data from elasticsearch using java api.

SearchResponse response = client.prepareSearch("dashboard")
.setFetchSource(new String[]{"aggregations"}, null)

Is there a way to get a specifig field from the response like the aggregation field...
(i know about parsing the json text, I am just asking about a common and better solution you are using)

Thank you in advence,

If you include a field in the query it's available in the response for each search hit:

SearchRequestBuilder requestBuilder = client.prepareSearch("dashboard");
SearchResponse response = requestBuilder.execute().actionGet(timeout);
SearchHits hits = response.getHits();

for (SearchHit result : hits) {
    Map<String, SearchHitField> fields = result.getFields();
    SearchHitField field = fields.get("field1");

Hope that helps.

So you want to run the search but only get the aggregation back? Set the size to 0. In the master branch that method is called setSize. The aggregation should be available in the getAggregations method. The REST API has response filtering but I believe that is a thing implemented on the REST layer so it doesn't have an analog in the java API.

Thank you guys,

Bruce_Ritchie that helped me a lot with getting the exact field in a search using a query.

nik9000, i used the size to reduce the hits wich i dont need for now , but is there a way to ensure that i get all the hits when i use a filter ?

And to get the aggregation fields this worked well for me:

  		Terms  terms = response.getAggregations().get("aggsName");
	        Collection<Terms.Bucket> buckets = terms.getBuckets();
                for (Bucket bucket : buckets) {
       System.out.println(bucket.getKeyAsString() +" ("+bucket.getDocCount()+")");

I love your team :smiley: