# \[SOLVED\] Java ES set addFields fetch the result is null

**URL:** <https://discuss.elastic.co/t/solved-java-es-set-addfields-fetch-the-result-is-null/49130>\
**Category:** Elasticsearch\
**Created:** [May 4, 2016, 7:05am UTC](https://discuss.elastic.co/t/solved-java-es-set-addfields-fetch-the-result-is-null/49130 "2016-05-04T07:05:56Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Xuan\_Yi](https://avatars.discourse-cdn.com/v4/letter/x/8797f3/32.png) [@Xuan\_Yi](https://discuss.elastic.co/u/Xuan_Yi)\
**Post date:** [May 4, 2016, 7:05am UTC](https://discuss.elastic.co/t/solved-java-es-set-addfields-fetch-the-result-is-null/49130/1 "2016-05-04T07:05:56Z")

</div>

hello ,I use the search API,just want to get some fileds and set the addFields method.like this,  
client.prepareSearch(index).setTypes(type).addFields(fields).setQuery(queryBuilder).setSize(sizeLimit).setExplain(true).get();  
but when I get the result that is null.  
for(SearchHit hit:response.getHits().getHits()){  
Map\<String, Object\> hitsMap = hit.getSource();  
[log.info](http://log.info)("["+hitsMap+"]");  
}  
I try to set the setSearchType(SearchType.QUERY\_AND\_FETCH) method ,or set the QUERY\_THEN\_FETCH ....but it does not work.  
version:2.3.0

---

<div class="post-metadata">

**Author:** ![warkolm](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/warkolm/32/39224_2.png) [@warkolm](https://discuss.elastic.co/u/warkolm)\
**Post date:** [May 4, 2016, 9:35am UTC](https://discuss.elastic.co/t/solved-java-es-set-addfields-fetch-the-result-is-null/49130/2 "2016-05-04T09:35:01Z")

</div>

How did you solve it?

---

<div class="post-metadata">

**Author:** ![Xuan\_Yi](https://avatars.discourse-cdn.com/v4/letter/x/8797f3/32.png) [@Xuan\_Yi](https://discuss.elastic.co/u/Xuan_Yi)\
**Post date:** [May 4, 2016, 9:46am UTC](https://discuss.elastic.co/t/solved-java-es-set-addfields-fetch-the-result-is-null/49130/3 "2016-05-04T09:46:42Z")

</div>

Actually I ignore something. When we set the addFields method,we can't fetch the result use that kind of method. It should be like this.

[Code]:  
for(SearchHit hit:response.getHits().getHits()){  
if( null != fields ){  
Set\<Entry\<String, SearchHitField\>\> fieldEntry = hit.getFields().entrySet();  
JSONObject json = new JSONObject();  
for(Entry\<String, SearchHitField\> entry:fieldEntry){  
json.put(entry.getValue().getName(), entry.getValue().getValue());  
}  
[log.info](http://log.info)("["+json+"]");   
}else{  
[log.info](http://log.info)(hit.getSourceAsString());  
}  
}  
}

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 10:53pm UTC](https://discuss.elastic.co/t/solved-java-es-set-addfields-fetch-the-result-is-null/49130/4 "2017-07-05T22:53:53Z")

</div>


