背景
ES在查询时如果数量太多,而每行记录包含的字段很多,那就会导致超出ES的查询上线,默认是100MB,但是很多场景下我们只需要返回特定的字段即可,那么如何操作呢。
主要代码
代码语言:javascript复制@Autowired
private RestHighLevelClient client;
public List<Map<String,Object>> search(String index) {
List<Map<String,Object>> hitList = new ArrayList();
try {
//搜索请求
SearchRequest request = new SearchRequest(index);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//查询某字段不为空
boolQueryBuilder.must(QueryBuilders.boolQuery().must((QueryBuilders.existsQuery("字段" ".keyword"))));
//查询指定字段
String[] fields = {"字段1","字段2"};
sourceBuilder.fetchSource(fields,null);
//把查询添加放入请求中
sourceBuilder.query(boolQueryBuilder);
request.source(sourceBuilder);
//查询数量
sourceBuilder.size(10000);
sourceBuilder.trackTotalHits(true);
//建立SearchResponse
SearchResponse response;
response = client.search(request, RequestOptions.DEFAULT);
//封装查询的信息
for (SearchHit hit : response.getHits().getHits()) {
hitList.add(hit.getSourceAsMap());
log.debug("查询结果:{}", hit.getSourceAsString());
}
} catch (IOException e) {
e.printStackTrace();
}
return hitList;
}
String[] fields = {“字段1”,“字段2”};
sourceBuilder.fetchSource(fields,null);
注意:字段不是实体类中的字段,而是表中的名称,不是userStatus而是user_status
本篇文章如有帮助到您,请给「翎野君」点个赞,感谢您的支持。
首发链接: https://cloud.tencent.com/developer/article/2356325