SpringBoot,Elasticsearch,读取查询结果(实体数据)返回的最简单最优美的方式:
@Autowired
ObjectMapper objectMapper;
@Resource
RestHighLevelClient elasticsearchClient;
@Override
public List<PagePerformance> findByUrl(String url) {
List<PagePerformance> ret = new ArrayList<>();
SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(createMatcher("url", url));
searchRequest.source(sourceBuilder);
RequestOptions options = RequestOptions.DEFAULT;
try {
SearchResponse searchResponse = elasticsearchClient.search(searchRequest, options);
ret = buildResponse(searchResponse, elasticsearchClient);
} catch (IOException e) {
Log.debug("PagePerformanceServiceImpl.findByUrl() 错误: " + e.getMessage());
}
return ret;
}
private <T> List<T> buildResponse(SearchResponse searchResponse, RestHighLevelClient client) {
List<T> ret = new ArrayList<T>();
searchResponse.getHits().forEach(item -> {
GetRequest getRequest = new GetRequest(item.getIndex(), item.getType(), item.getId());
try {
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
if (getResponse.isExists())
ret.add(objectMapper.readValue(getResponse.getSourceAsString(), new TypeReference<T>() {
}));
} catch (IOException e) {
e.printStackTrace();
}
});
return ret;
}