先記錄下實例spring
配置文件maven
spring.data.solr.host=http://localhost:8983/solr
maven依賴
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-solr</artifactId> <version>${spring.data.solr.version}</version> </dependency>
/** * @Author: liuxs * @Description: 經過solr檢索銀行信息 * @Date: Create in 18:28 2018/7/30. */ @Service public class BankSolrService { @Autowired private BankRepository bankRepository; @Autowired private SolrClient solrClient; public List<BankBranch> queryBranch(QueryBankBean queryBean) throws Exception { List<BankBranch> bankBranches = new ArrayList<>(); QueryResponse response = solrClient.query("my_core", convertQuery(queryBean)); SolrDocumentList results = response.getResults(); // 數量,分頁用 long total = results.getNumFound(); for (SolrDocument document : results) { bankBranches.add(covertBankBranch(document)); } return bankBranches; } /** * 整合檢索參數 * @param queryBean * @return * todo 硬編碼抽出 */ public SolrQuery convertQuery(QueryBankBean queryBean) { SolrQuery solrQuery = new SolrQuery(); if (StringUtils.isEmpty(queryBean.getBankName())) { throw new RuntimeException("銀行名稱不能爲空"); } if (StringUtils.isEmpty(queryBean.getBranchName())) { throw new RuntimeException("銀行支行名稱不能爲空"); } String bankCode = bankRepository.findBankCodeByAliasName(queryBean.getBankName()); solrQuery.setQuery("branchName=" + queryBean.getBankName() + queryBean.getBranchName()); solrQuery.addFilterQuery("bankCode=" + bankCode); //分頁,默認10條每頁 solrQuery.setRows(queryBean.getSize()); if (StringUtils.isEmpty(queryBean.getPage())) { solrQuery.setStart(0); } else { solrQuery.setStart(queryBean.getPage() * solrQuery.getRows()); } return solrQuery; } /** * Document To Object * @param d * @return */ private BankBranch covertBankBranch(SolrDocument d) { BankBranch branch = new BankBranch(); branch.setRelateCode(d.containsKey("relateCode") ? String.valueOf(d.get("relateCode")) : ""); branch.setBranchName(d.containsKey("branchName") ? String.valueOf(d.get("branchName")) : ""); branch.setBankCode(d.containsKey("bankCode") ? String.valueOf(d.get("bankCode")) : ""); branch.setBankName(d.containsKey("bankName") ? String.valueOf(d.get("bankName")) : ""); branch.setProvinceCode(d.containsKey("provinceCode") ? String.valueOf(d.get("provinceCode")) : ""); branch.setProvinceName(d.containsKey("provinceName") ? String.valueOf(d.get("provinceName")) : ""); branch.setCityCode(d.containsKey("cityCode") ? String.valueOf(d.get("cityCode")) : ""); branch.setCityName(d.containsKey("cityName") ? String.valueOf(d.get("cityName")) : ""); return branch; } }