import java.io.IOException; import java.util.HashMap; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.solr.client.solrj.SolrClient; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.Http2SolrClient; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.params.MapSolrParams; public class Searcher { private static final Logger LOGGER = LogManager.getLogger(Searcher.class); private SolrClient solrClient; public Searcher(String url, String user, String password) { solrClient = new Http2SolrClient.Builder(url) .connectionTimeout(10000) .withBasicAuthCredentials(user, password) .build(); } public SearchResultSet search(String query, String collection, long offset, int limit) { final MapSolrParams queryParams = new MapSolrParams(new HashMap() { { // https://solr.apache.org/guide/solr/latest/query-guide/standard-query-parser.html put("q", query); // put("q.op", "OR"); put("df", "lemma4search"); // pagination // https://solr.apache.org/guide/solr/latest/query-guide/pagination-of-results.html put("start", String.valueOf(offset)); // starts with 0 put("rows", String.valueOf(limit)); // highlighting // https://solr.apache.org/guide/solr/latest/query-guide/highlighting.html put("hl", "true"); put("hl.fl", "dataview_hits"); // only highlight on "dataview_hits" put("hl.fragsize", "0"); // whole field put("hl.simple.pre", ""); // no prefix so that we can parse more easily put("hl.simple.post", ""); } }); try { final QueryResponse response = solrClient.query(collection, queryParams); final long total = response.getResults().getNumFound(); final List entries = response.getBeans(ResultEntry.class); // process highlighting (update dataview_hits) for (ResultEntry entry : entries) { if (!response.getHighlighting().containsKey(entry.id)) { continue; } final List highlights = response.getHighlighting().get(entry.id).get("dataview_hits"); if (highlights == null || highlights.size() == 0) { continue; } final String highlight = highlights.get(0); entry.dataview_hits = highlight; } LOGGER.debug("results: {}", entries); return new SearchResultSet(collection, query, entries, total, offset); } catch (SolrServerException | IOException e) { LOGGER.error("Solr request error", e); } return null; } }