I have used RestHighLevelClient to search and retrieve data as List<Map<String, Object>>.
final SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
RestStatus statusCode = response.status();
log.info("Status code : {} ", statusCode.getStatus());
if(RestStatus.OK.equals(response.status())) {
final SearchHits hits = response.getHits();
Long totalHits = hits.getTotalHits();
log.info("Total number of hits : {} ", totalHits);
final SearchHit[] results = hits.getHits();
List<Map<String, Object>> list = new ArrayList<>(totalHits.intValue());
for(SearchHit hit : results) {
final Map<String, Object> sourceAsMap = hit.getSourceAsMap();
list.add(sourceAsMap);
}
return list;
}
The signature of search() in ElasticSearchClient is different. It requires to provide Class as a part of the method parameter. In my case, I do not want to cast it into any concrete object. I tried to use "Object.class" (e.g. elasticSearchClient.search(searchRequest, Object.class). But It did not provide me the list of Map which I used to get in RestHighLevelClient. My question is how do I extract the List<Map <String, Object>> from the response using the new API?
SearchResponse<Object> response = elasticSearchClient.search(searchRequest, Object.class);
List<Hit<Object>> hits = response.hits().hits();
for (Hit<Object> hit : hits) {
// how do I get Map<String, Object> here?
}
You can also use the ObjectNode
class:
ObjectNode json = response.source();
String name = json.get("name").asText();
logger.info("Product name " + name);
Source: documentation