因为字段太多,所以需要对结果的个别字段进行返回,尝试用addFields和getField来实现,但是无论如果返回结果都是null,但是尝试直接getSource,获取整个souce是有值的,debug调试过,Hits数组里面也是有值的,请教下各位:
public Map<String, Object> searchField(String index, String type, ESQueryBuilderConstructor constructor,String field){
client = ESUtils.ES_UTILS.getClient();
Map<String, Object> results = new HashMap<>();
SearchRequestBuilder searchRequestBuilder =
client.prepareSearch(index).setTypes(type).setVersion(Boolean.TRUE);
//排序
if (StringUtils.isNotEmpty(constructor.getAsc())) {
searchRequestBuilder.addSort(constructor.getAsc(), SortOrder.ASC);
}
if(StringUtils.isNotEmpty(constructor.getDesc())) {
searchRequestBuilder.addSort(constructor.getDesc(), SortOrder.DESC);
}
SearchResponse response = searchRequestBuilder.execute().actionGet();
//设置查询体
searchRequestBuilder.setQuery(constructor.listBuilder()).addField(field);
//返回条目数
int size = constructor.getSize();
if (size<0) {
size = 0;
}
if (size>MAX) {
size = MAX;
}
SearchHits hits = response.getHits();
SearchHit[] searchHits = hits.getHits();
for (SearchHit sh : searchHits) {
Set<Map.Entry<String, SearchHitField>> fieldEntry = sh.getFields().entrySet();
for(Map.Entry<String, SearchHitField> entry:fieldEntry){
System.out.println(entry.getValue().getName()+" "+entry.getValue().getValue());
results.put(entry.getValue().getName(), entry.getValue().getValue());
}
}
return results;
}
1 个回复
jianjianhe
赞同来自: novia 、medcl
searchRequestBuilder.setQuery(constructor.listBuilder()).addField(field);这行代码放到SearchResponse response = searchRequestBuilder.execute().actionGet();后面了,导致没有将searchRequestBuilder这个查询体放进去,而是直接去执行了searchRequestBuilder,结果导致getFileds方法没有值,而source里面有值,完全是代码逻辑的问题
最后,修改代码顺序能够正确返回需要的字段值。
最后将正确代码贴出来,供各位参考:
代码中的:
ESQueryBuilderConstructor其实就是封装的一个我们需要构建的QueryBuilder查询逻辑体