Solr7.4.0的API(Solrj)操做及項目中的使用

一.SolrJ的概念

solr單機版服務搭建:http://www.javashuo.com/article/p-ompcnpwa-mg.htmlhtml

solr集羣版服務搭建:http://www.javashuo.com/article/p-svunygwj-e.htmlnode

        SolrJ是一個API,它使用Java(或任何基於JVM的語言)編寫的應用程序能夠輕鬆地與Solr交談。SolrJ隱藏了許多鏈接到Solr的細節,並容許您的應用程序經過簡單的高級方法與Solr交互。SolrJ支持大多數Solr API,而且具備高度可配置性。apache

官方API參考文檔: http://lucene.apache.org/solr/guide/7_4/using-solrj.html#using-solrjide

這裏使用Maven構建項目,請將如下內容放入pom.xml單元測試

<dependency>
  <groupId>org.apache.solr</groupId>
  <artifactId>solr-solrj</artifactId>
  <version>7.4.0</version>
</dependency>

爲了方便測試,導入單元測試依賴和日誌依賴測試

複製代碼
<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.25</version>
</dependency>
複製代碼

二.SolrJ的單機鏈接

SolrClient是一個抽象類,下邊有不少被實現的子類,HttpSolrClient - 面向以查詢爲中心的工做負載,但也是一個很好的通用客戶端。直接與單個Solr節點通訊。ui

不一樣solr版本solrj 的建立方式有所不一樣url

//solr4建立方式
SolrServer solrServer = new HttpSolrServer(solrUrl); 
//solr5建立方式,在url中指定core名稱:core1
HttpSolrClient solrClient = new HttpSolrClient(solrUrl);
//solr7建立方式,在url中指定core名稱:core1
HttpSolrClient solrClient = new HttpSolrClient.Builder(solrUrl).build();

例如:spa

複製代碼
package com.xyg.solr;

import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.junit.Test;

/**
 * Author: Mr.Deng
 * Date: 2018/9/10
 * Desc: 測試鏈接客戶端
 */
public class testConnectionClient {

    @Test
    public void testConnectionClient(){
        //設置solr客戶端url地址
        String solrUrl = "http://node21:8080/solr/new_core";
        //建立solrClient同時指定超時時間,不指定走默認配置
        HttpSolrClient solrClient = new HttpSolrClient.Builder(solrUrl)
                .withConnectionTimeout(10000)
                .withSocketTimeout(60000)
                .build();
        System.out.println(solrClient);
    }
}
複製代碼

三.SolrJ的集羣鏈接

 CloudSolrClient - 面向與SolrCloud部署的通訊。使用已記錄的ZooKeeper狀態來發現並將請求路由到健康的Solr節點。3d

複製代碼
package com.xyg.solrCloud;

import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.junit.Test;

/**
 * Author: Mr.Deng
 * Date: 2018/9/10
 * Desc: 測試鏈接客戶端
 */
public class ConnectionCloudSolrClient {

    @Test
    public void connectionCloudSolrClient(){
        // 第一種方式:使用運行中的某一臺solr節點
        //final String solrUrl = "http://192.168.100.21:8983/solr";
        //CloudSolrClient solrClient = new CloudSolrClient.Builder().withSolrUrl(solrUrl).build();

        // 第二種方式:使用zookeeper節點鏈接(推薦)
        final String zkHost = "node21:2181,node22:2181,node23:2181/solr";
        CloudSolrClient solrClient = new CloudSolrClient.Builder().withZkHost(zkHost).build();
        System.out.println(solrClient);
    }
}
複製代碼

四.SolrJ的增刪改查

這裏測試單機版APi操做

1.建立索引

1)指定id單條建立索引 

複製代碼
@Test
public void addIndexById() throws IOException, SolrServerException {
    String solrUrl = "http://node21:8080/solr/new_core";
    HttpSolrClient solrClient = new HttpSolrClient.Builder(solrUrl).build();
    //建立索引文檔對象
    SolrInputDocument doc = new SolrInputDocument();
    // 第一個參數:域的名稱,域的名稱必須是在schema.xml中定義的
    // 第二個參數:域的值,注意:id的域不能少
    doc.addField("id","1");
    doc.addField("name","紅豆");
    doc.addField("price","1.2");
    //3.將文檔寫入索引庫中
    solrClient.add(doc);
    solrClient.commit();
}
複製代碼

2)批量建立索引 

複製代碼
@Test
public void addIndexByListId() throws Exception {
    String solrUrl = "http://node21:8080/solr/new_core";
    HttpSolrClient solrClient = new HttpSolrClient.Builder(solrUrl).build();
    //建立索引文檔對象
    SolrInputDocument doc1 = new SolrInputDocument();
    doc1.addField( "id", "2");
    doc1.addField( "name", "綠豆");
    doc1.addField( "price", 1.8 );
    SolrInputDocument doc2 = new SolrInputDocument();
    doc2.addField( "id", "3" );
    doc2.addField( "name", "黑豆" );
    doc2.addField( "price", 2.6 );
    Collection<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
    docs.add(doc1);
    docs.add(doc2);
    //3.將文檔寫入索引庫中
    solrClient.add(docs);
    solrClient.commit();
}
複製代碼

2.查詢索引

1)匹配查詢

複製代碼
    @Test
    public void findIndex1() throws IOException, SolrServerException {
        String solrUrl = "http://node21:8080/solr/new_core";
        HttpSolrClient solrClient = new HttpSolrClient.Builder(solrUrl).build();
        // 建立搜索對象
        SolrQuery query = new SolrQuery();
        // 設置搜索條件
        query.set("q","*:*");
        //設置每頁顯示多少條
        query.setRows(2);
        //發起搜索請求
        QueryResponse response = solrClient.query(query);
        // 查詢結果
        SolrDocumentList docs = response.getResults();
        // 查詢結果總數
        long cnt = docs.getNumFound();
        System.out.println("總條數爲"+cnt+"條");
        for (SolrDocument doc : docs) {
          System.out.println("id:"+ doc.get("id") + ",name:"+ doc.get("name") + ",price:"+ doc.get("price"));
        }
        solrClient.close();
    }
複製代碼

2)條件過濾查詢

複製代碼
 @Test
    public void findIndex2() throws IOException, SolrServerException {
        String solrUrl = "http://node21:8080/solr/new_core";
        HttpSolrClient solrClient = new HttpSolrClient.Builder(solrUrl).build();
        //2 封裝查詢參數
        Map<String, String> queryParamMap = new HashMap<String, String>();
        queryParamMap.put("q", "*:*");
        //3 添加到SolrParams對象,SolrParams 有一個 SolrQuery 子類,它提供了一些方法極大地簡化了查詢操做
        MapSolrParams queryParams = new MapSolrParams(queryParamMap);
        //4 執行查詢返回QueryResponse
        QueryResponse response = solrClient.query(queryParams);
        //5 獲取doc文檔
        SolrDocumentList docs = response.getResults();
        // 查詢結果總數
        long cnt = docs.getNumFound();
        System.out.println("總條數爲" + cnt + "條");
        //[6]內容遍歷
        for (SolrDocument doc : docs) {
            System.out.println("id:" + doc.get("id") + ",name:" + doc.get("name") + ",price:" + doc.get("price"));
        }
        solrClient.close();
    }
複製代碼

3.更新索引

複製代碼
    @Test
    public void updateIndex() throws IOException, SolrServerException {
        String solrUrl = "http://node21:8080/solr/new_core";
        HttpSolrClient solrClient = new HttpSolrClient.Builder(solrUrl).build();
        //建立索引文檔對象
        SolrInputDocument doc = new SolrInputDocument();
        //把紅豆價格修改成1.5
        doc.addField("id","1");
        doc.addField("name","紅豆");
        doc.addField("price","1.5");
        //3.將文檔寫入索引庫中
        solrClient.add(doc);
        solrClient.commit();
        //提交
        solrClient.commit();

    }
複製代碼

4.刪除索引 

1)單一條件刪除

複製代碼
    @Test
    public void deleteIndexById() throws IOException, SolrServerException {
        String solrUrl = "http://node21:8080/solr/new_core";
        HttpSolrClient solrClient = new HttpSolrClient.Builder(solrUrl).build();
        //全刪
        //solrClient.deleteByQuery("*:*");
        //模糊匹配刪除(帶有分詞效果的刪除)
        solrClient.deleteByQuery("name:紅");
        //指定id刪除
        //solrClient.deleteById("1");
        solrClient.commit();
    }
複製代碼

2)批量條件刪除

複製代碼
    @Test
    public void deleteIndexByListId() throws IOException, SolrServerException {
        String solrUrl = "http://node21:8080/solr/new_core";
        HttpSolrClient solrClient = new HttpSolrClient.Builder(solrUrl).build();
        //經過id刪除
        ArrayList<String> ids = new ArrayList<String>();
        ids.add("2");
        ids.add("3");
        solrClient.deleteById(ids);
        //[3]提交
        solrClient.commit();
        //[4]關閉資源
        solrClient.close();
    }
複製代碼

五.代碼報錯問題

1.代碼添加索引報405問題

解決方法:

在使用Tomcat部署Solr後,new_core的地址爲:http://node21:8080/solr/#/new_core,但使用SolrJ進行索引的時候,應該使用http://node21:8080/solr/new_core,即無中間的#號。

2.自定義索引字段

上圖報錯提示未識別索引字段

 

參考文檔:

https://www.w3cschool.cn/solr_doc/solr_doc-g1az2fmd.html

http://www.javashuo.com/article/p-uidyxoly-mh.html

https://www.jianshu.com/p/11fb9cfdb2fd

相關文章
相關標籤/搜索