use of com.erudika.para.server.search.es.ESUtils.getPager in project para-search-elasticsearch by Erudika.
the class ES method searchQueryRaw.
/**
* Executes an ElasticSearch query. This is the core method of the class.
* @param appid name of the {@link com.erudika.para.core.App}
* @param type type of object
* @param query the search query builder
* @param pager a {@link com.erudika.para.core.utils.Pager}
* @return a list of search results
*/
protected static SearchResponse<Map> searchQueryRaw(String appid, String type, QueryVariant query, Pager... pager) {
if (StringUtils.isBlank(appid)) {
return null;
}
Pager page = ESUtils.getPager(pager);
SortOrder order = page.isDesc() ? SortOrder.Desc : SortOrder.Asc;
int max = page.getLimit();
int pageNum = (int) page.getPage();
int start = (pageNum < 1 || pageNum > Para.getConfig().maxPages()) ? 0 : (pageNum - 1) * max;
if (query == null) {
query = QueryBuilders.matchAll().build();
}
if (!StringUtils.isBlank(type)) {
query = QueryBuilders.bool().must(query._toQuery(), QueryBuilders.term().field(Config._TYPE).value(v -> v.stringValue(type)).build()._toQuery()).build();
}
SearchResponse<Map> hits = null;
String debugQuery = "";
try {
SearchRequest.Builder search = new SearchRequest.Builder();
search.index(getIndexName(appid)).searchType(SearchType.DfsQueryThenFetch).query(query._toQuery()).size(max).trackTotalHits(ESUtils.getTrackTotalHits());
if (pageNum <= 1 && !StringUtils.isBlank(page.getLastKey())) {
search.searchAfter(page.getLastKey());
search.from(0);
search.sort(SortOptions.of(b -> b.field(f -> f.field("_docid").order(order))));
} else {
search.from(start);
for (SortOptions sortField : ESUtils.getSortFieldsFromPager(page)) {
search.sort(sortField);
}
}
debugQuery = search.toString();
logger.debug("Elasticsearch query: {}", debugQuery);
hits = getRESTClient().search(search.build(), Map.class);
page.setCount(Optional.ofNullable(hits.hits().total()).orElse(TotalHits.of(t -> t.relation(TotalHitsRelation.Eq).value(page.getCount()))).value());
if (hits.hits().hits().size() > 0) {
Object id = hits.hits().hits().get(hits.hits().hits().size() - 1).source().get("_docid");
if (id != null) {
page.setLastKey(id.toString());
}
}
} catch (Exception e) {
Throwable cause = e.getCause();
String msg = cause != null ? cause.getMessage() : e.getMessage();
logger.debug("No search results for type '{}' in app '{}': {}.\nQuery: {}", type, appid, msg, debugQuery);
}
return hits;
}
Aggregations