String [] excludes = {"field0"};
String [] includes = {"field1","field2"};
SearchResponse searcher = client.getClient().prepareSearch(INDEX).setFetchSource(includes, excludes).setQuery(qb).execute().actionGet();
If you do not include the "addFields()" command, you will not be able to iterate over the fields of the hits. However, you can iterate using "sourceAsMap()".
for (SearchHit hit : searcher.getHits().getHits()) {
Map
for (String key : hits.keySet()) {
//do something
}
Object [] fieldValues = hits.values().toArray();
for (Object fieldValue:fieldValues) {
//do something
}
}
As you will notice, the excluded fields at "excludes" will not show up. Also, if you try "hit.getFields()" it will be empty.
References:
http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/mapping-source-field.html
https://github.com/elasticsearch/elasticsearch/blob/master/src/test/java/org/elasticsearch/search/source/SourceFetchingTests.java