我设法通过查看 SolrTemplate 类的源代码使其工作,但我想知道是否有一个侵入性较小的解决方案。
public Page<Document> searchDocuments(DocumentSearchCriteria criteria, Pageable page) {
String[] words = criteria.getTitle().split(" ");
Criteria conditions = createSearchConditions(words);
SimpleQuery query = new SimpleQuery(conditions);
query.setPageRequest(page);
SolrQuery solrQuery = queryParsers.getForClass(query.getClass()).constructSolrQuery(query);
solrQuery.add(AUTHENTICATED_USER_NAME, criteria.getLoggedUsername());
try {
String queryString = this.queryParsers.getForClass(query.getClass()).getQueryString(query);
solrQuery.set(CommonParams.Q, queryString);
QueryResponse response = solrTemplate.getSolrServer().query(solrQuery);
List<Document> beans = convertQueryResponseToBeans(response, Document.class);
SolrDocumentList results = response.getResults();
return new SolrResultPage<>(beans, query.getPageRequest(), results.getNumFound(), results.getMaxScore());
} catch (SolrServerException e) {
log.error(e.getMessage(), e);
return new SolrResultPage<>(Collections.<Document>emptyList());
}
}
private <T> List<T> convertQueryResponseToBeans(QueryResponse response, Class<T> targetClass) {
return response != null ? convertSolrDocumentListToBeans(response.getResults(), targetClass) : Collections
.<T> emptyList();
}
public <T> List<T> convertSolrDocumentListToBeans(SolrDocumentList documents, Class<T> targetClass) {
if (documents == null) {
return Collections.emptyList();
}
return solrTemplate.getConverter().read(documents, targetClass);
}
private Criteria createSearchConditions(String[] words) {
return new Criteria("title").contains(words)
.or(new Criteria("description").contains(words))
.or(new Criteria("content").contains(words))
.or(new Criteria("resourcename").contains(words));
}