參考官方文檔或前文教程完成 Solr 5.5.3 服務部署,確保 Core/Collection 正常運行。
<dependency>
<groupId>org.apache.solr</groupId>
<artifactId>solr-solrj</artifactId>
<version>5.5.3</version>
</dependency>
或手動導入 solr-5.5.3/dist/solrj-lib/ 目錄下所有 JAR 包,含 solr-solrj-5.5.3.jar。
以下為 Spring MVC Controller 示例,支持關鍵字搜索與分頁:
@ResponseBody
@RequestMapping(value = "/searchByKeyWord", method = {RequestMethod.POST, RequestMethod.GET}, produces = "application/json; charset=utf-8")
public String search(HttpServletRequest request, HttpServletResponse response,
String keyWord, int pageSize, int pageOffset) {
try {
// 1. 獲取 Solr 服務地址(建議配置文件注入)
String solrUrl = ConfigUtil.getValueByKey("solrServiceUrl");
SolrClient solr = new HttpSolrClient.Builder(solrUrl).build();
// 2. 構建查詢參數
SolrQuery query = new SolrQuery();
query.set("q", URLDecoder.decode(keyWord, "UTF-8")); // 搜索關鍵字
query.setStart(pageOffset * pageSize); // 分頁起始行
query.setRows(pageSize); // 每頁條數
// 3. 執行查詢
QueryResponse queryResponse = solr.query(query);
// 4. 封裝結果
Map<String, Object> result = new HashMap<>();
List<OCSearchObject> list = queryResponse.getBeans(OCSearchObject.class);
result.put("success", true);
result.put("key", URLDecoder.decode(keyWord, "UTF-8"));
result.put("list", list);
result.put("totalCount", queryResponse.getResults().getNumFound());
solr.close();
return json(result);
} catch (Exception e) {
LOGGER.error("Solr 查詢異常", e);
return jsonpFalse(request, response, "code_error");
}
}
public class OCSearchObject {
private Long id;
private String name;
private String fullText;
private String type;
// Getter 省略...
@Field("id")
public void setId(Long id) { this.id = id; }
@Field("name")
public void setName(String name) { this.name = name; }
@Field("fullText")
public void setFullText(String fullText) { this.fullText = fullText; }
@Field("type")
public void setType(String type) { this.type = type; }
}
注意: @Field 值必須與 Solr schema.xml / managed-schema 中定義的字段名完全一致,且與 data-config.xml 導入配置對應。
totalCount 實現翻頁。| 問題 | 解決方案 |
|---|---|
| 中文亂碼 | 確保 Solr、JVM、DB、前端統一 UTF-8;URLDecoder 解碼關鍵字。 |
| 查詢慢 | 優化 schema(索引字段類型、copyField)、啟用 Filter Cache、調大 heap、使用 SolrCloud 分片。 |
| 實體映射失敗 | 檢查 @Field 名稱、字段類型匹配(Long vs String)、無參構造器是否存在。 |
| 連接洩漏 | 使用 try-with-resources 或 finally 關閉 SolrClient;生產環境建議單例或連接池。 |
SolrJ 5.5.3 提供了豐富的 Java API,配合 Spring MVC 可快速構建企業級搜索服務。關鍵在於 Schema 設計、實體映射正確、分頁參數規範、異常處理完善。後續可擴展高亮、拼寫建議、分面搜索等高級功能。