I already provided ElasticSearchConfig class which will return RESTHighLevelClient object and below method only will be called from Spring boot controller. Please let me know if need anything else.
public List searchWithES(String indexName, Map<String, String> requestParams) throws IOException {
SearchRequest searchRequest = new SearchRequest(indexName.toLowerCase());
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
BoolQueryBuilder subBool = QueryBuilders.boolQuery();
// Search with enterprise set/Index name which should not have "_" or
// Search with source set to validate MISSING field name
if (requestParams != null && requestParams.size() > 0) {
requestParams.forEach((k, v) -> {
if (!tempList.contains(k)) {
if (indexName.endsWith("_map")) {
subBool.must(
QueryBuilders.matchQuery("json_from_csv.Source_" + k + ".keyword", v == null ? "" : v));
} else {
subBool.should(QueryBuilders.matchQuery("json_from_csv." + k + ".keyword", v == null ? "" : v));
}
}
});
searchSourceBuilder.query(subBool);
} else if (!indexName.contains("_") || requestParams == null) {
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
}
searchSourceBuilder.fetchSource(null, excludeDefaultFields.split(","));
searchSourceBuilder.size(indexName.contains("_") && requestParams == null ? 1 : pagecount);
searchRequest.scroll(scroll);
searchRequest.source(searchSourceBuilder);
List<Object> outputList = new ArrayList<>();
LOGGER.info("Search JSON query: {}\n" + searchRequest.source().toString());
System.out.println("Search JSON query: {}\n" + searchRequest.source().toString());
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
String scrollId = searchResponse.getScrollId();
SearchHit[] searchHits = searchResponse.getHits().getHits();
while (searchHits != null && searchHits.length > 0) {
Arrays.stream(searchHits).forEach(hit -> outputList.add(hit.getSourceAsMap().get("json_from_csv")));
if (searchSourceBuilder.size() == 1) {
break;
}
SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
scrollRequest.scroll(scroll);
searchResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT);
scrollId = searchResponse.getScrollId();
searchHits = searchResponse.getHits().getHits();
}
return outputList;
}