solrj是訪問Solr服務的java客戶端,提供索引和搜索的請求方法,如下圖:(Solrj和圖形界面操作的區別就類似於數據庫中使用jdbc和mysql客戶端的區別一樣。)
環境準備
- Solr:4.10.3
- Jdk環境:1.7
- IDE環境:Eclipse Mars2
工程搭建
- 創建java工程
- 添加jar
Solrj的包,\solr-4.10.3\dist\目錄下
solrj依賴包,\solr-4.10.3\dist\solrj-lib
Solr服務的依賴包,\solr\example\lib\ext
代碼實現
1.增
/* * 創建HttpSolrServer對象,通過它和Solr服務器建立連接。 * 創建SolrInputDocument對象,然後通過它來添加域。 * 通過HttpSolrServer對象將SolrInputDocument添加到索引庫。 */ @Test public void testCreateAndUpdateIndex() throws Exception { // 1. 創建HttpSolrServer對象 // 設置solr服務接口,瀏覽器客戶端地址http://127.0.0.1:8081/solr/#/ String baseURL = "http://127.0.0.1:8787/solr"; HttpSolrServer httpSolrServer = new HttpSolrServer(baseURL); // 2. 創建SolrInputDocument對象 SolrInputDocument document = new SolrInputDocument(); document.addField("id", "c1001"); // 3. 把SolrInputDocument對象添加到索引庫中 httpSolrServer.add(document); // 4. 提交 httpSolrServer.commit(); }
2.刪/* * 刪除索引邏輯,兩種: * 根據id刪除 * 根據條件刪除,根據條件刪除 * 可以使用*:*作爲條件,就是刪除所有數據(慎用) */ // 提取HttpSolrServer創建 private HttpSolrServer httpSolrServer; @Before public void init() { // 1. 創建HttpSolrServer對象 // 設置solr服務接口,瀏覽器客戶端地址http://127.0.0.1:8787/solr/#/ String baseURL = "http://127.0.0.1:8787/solr/"; this.httpSolrServer = new HttpSolrServer(baseURL); } @Test public void testDeleteIndex() throws Exception { // 根據id刪除索引數據 // this.httpSolrServer.deleteById("c1001"); // 根據條件刪除(如果是*:*就表示全部刪除,慎用) this.httpSolrServer.deleteByQuery("*:*"); // 提交 this.httpSolrServer.commit(); }
3.查/** * 簡單搜索 * * @throws Exception */ @Test public void testSearchIndex1() throws Exception { // 創建搜索對象 SolrQuery query = new SolrQuery(); // 設置搜索條件 query.setQuery("*:*"); // 發起搜索請求 QueryResponse response = this.httpSolrServer.query(query); // 處理搜索結果 SolrDocumentList results = response.getResults(); System.out.println("搜索到的結果總數:" + results.getNumFound()); // 遍歷搜索結果 for (SolrDocument solrDocument : results) { System.out.println("----------------------------------------------------"); System.out.println("id:" + solrDocument.get("id")); System.out.println("content" + solrDocument.get("content")); } }