solrJ使用總結

1.solrJ概念

solrJ是Java連接solr進行查詢檢索和索引更新維護的jar包。

2.項目引入solrJ相關jar包

對於maven工程,直接將下面內容加入到pom文件中即可。

  1. <dependency>
  2. <groupId>org.apache.solr</groupId>
  3. <artifactId>solr-solrj</artifactId>
  4. <version>5.3.1</version>
  5. </dependency>

注意solrj編譯依賴下面jar包

非maven工程,可在solr安裝目錄下找到所有需要的jar包

3.主要用到的類接口簡介


如上圖SolrClient是所有類基類,裏面定義了更新維護索引、搜索相關的接口;LBHttpSolrClient用於有多個solr服務器時實現負載均衡的情況;ConcurrentUpdateSolrClient類是線程安全類,推薦在更新維護索引時用;HttpSolrClient用於獨立工作模式的solr的查詢;CloudSorlClient用於solrCould模式。以HttpSolrClient爲例說明主要接口的使用。

  • 初始化SolrClient對象
  1. //直接指定solr的URL和core1,只能查詢或更新core1內容
  2. SolrClient client = new HttpSolrClient("http://my-solr-server:8983/solr/core1");
  3. QueryResponse resp = client.query(new SolrQuery("*:*"));
  4. //指定solr的URL,查詢或更新時要指定core
  5. SolrClient client = new HttpSolrClient("http://my-solr-server:8983/solr");
  6. QueryResponse resp = client.query("core1", new SolrQuery("*:*"));
  • 更新維護索引的主要接口是

    1. addBean(Object obj)
    2. addBean(Object obj, int commitWithinMs)
    3. addBean(String collection, Object obj, int commitWithinMs)
    4. add(String collection, Collection<SolrInputDocument> docs, int commitWithinMs)
    5. add(String collection, SolrInputDocument doc, int commitWithinMs)

    該函數有多個重載形式,obj是要加入索引的實體對象,collection指定要操作的core,commitWithinMs要提交的毫秒數,默認爲-1,add後不會更新,要調用
    commit(String collection)提交後才能更新查詢到。

  • SolrInputDocument和Object之間轉換

  1. doc = getBinder().toSolrInputDocument(obj);
  2. objList =solr.getBinder().getBeans(CaseEntity.class, resp.getResults());
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章