@Resource
private RestHighLevelClient restHighLevelClient;
@SuppressWarnings("unchecked")
@Override
public List<T> esSearch(String index, String template, Map<String, Object> map) {
SearchTemplateRequest request = new SearchTemplateRequest();
request.setRequest(new SearchRequest(index));
request.setScriptType(ScriptType.STORED);
request.setScript(template);
request.setScriptParams(map);
List<T> res = new ArrayList<>();
try {
SearchTemplateResponse searchResponse = restHighLevelClient.searchTemplate(request, RequestOptions.DEFAULT);
if(null == searchResponse) {
return res;
}
SearchHits hits = searchResponse.getResponse().getHits();
res = (List<T>) Arrays.stream(hits.getHits()).map(hit -> {
return hit.getSourceAsMap();
}).collect(Collectors.toList());
} catch (Exception e) {
log.error("{ES查询异常}----->" + e);
}
return res;
}
Java 实现ES查询
最新推荐文章于 2024-09-26 15:28:48 发布
该代码段展示了如何使用@Resource注解注入的RestHighLevelClient执行Elasticsearch的搜索模板请求。方法接受索引名、模板、参数映射,通过ScriptType.STORED设置模板类型,然后处理响应,将SearchHit的源数据转换为List<T>返回。
摘要由CSDN通过智能技术生成