Solr4.10使用教程(三):solr crud

solr的增刪改查,啥都不說,直接代碼

package com.johnny.lucene06.solr;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrResponse;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;

public class SolrHelloWorldTest {
    //solr server URL指的時solr發佈到web工程後的訪問路徑
    private final static String SolrURL = "http://localhost:8080/solr";
    
    private HttpSolrServer solrServer = null;
    /**如果要使用下面的test,需要確保solr的tomcat服務器以已經啓動**/
    //使用Field添加doc
    @Test
    public void test01(){
        try {
            /**1、創建solrServer(HttpSolrServer和EmbeddedSolrServer)
             * 其中HttpSolrServer必須依賴tomcat等WEB容器,EmbeddedSolrServer則不需要,但是需要
             * 引入其它jar包,具體可以參照doc下得solr wiki.html
             * **/
            HttpSolrServer server = getSolrServer();
            server.deleteByQuery("*:*");//先刪除默認數據,防止對理解產生混淆
            /**2、solr要求doc的Field中必須存在一個Field爲id,並且值爲java.lang.String類型
             * 並且要保證Id的唯一,否則最後添加的相同Id的域會覆蓋前面的域,也就等於是更新
             * **/
            SolrInputDocument doc = new SolrInputDocument();
            doc.addField("id",String.valueOf(1));
            /**3、對於需要使用doc添加的Field,必須先在schema.xml中進行配置,然後纔可以使用,
             * 關於schema的配置說明,可以參照lucene-solr.txt中得說明
             * **/
            doc.addField("my_title","這是我的solr Hello world ");
            doc.addField("my_content","大家好,歡迎查看我的第一篇solr text");
            server.add(doc);
            SolrInputDocument doc2 = new SolrInputDocument();
            doc2.addField("id", String.valueOf(2));
            doc2.addField("my_title","我是中國人 ");
            doc2.addField("my_content","我愛你,偉大的祖國,我愛北京天安門 hello");
            server.add(doc2);
            server.commit();//提交,將所有更細提交到索引中
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //solrServer是線程安全的,所以在使用時需要使用單例的模式,減少資源的消耗
    public HttpSolrServer getSolrServer(){
        if(solrServer==null){
            solrServer = new HttpSolrServer(SolrURL);
        }
        return solrServer;
    }
    
    /**
     * 使用POJO添加document
     */
    @Test
    public void testAddDocumentByObject(){
        try {
            HttpSolrServer server = getSolrServer();
            List<Message> msgs = new ArrayList<Message>();
            msgs.add(new Message("3","測試Hello POJO添加", "pojo應該可以添加成功"));
            msgs.add(new Message("4","Hello,我又添加了一條","現在Id已經是4了"));
            msgs.add(new Message("5", "我已經添加5條記錄了", "hello ok,在添加我就吐了。。"));
            server.addBeans(msgs);
            server.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**修改記錄,
     * 修改時是按照Id進行覆蓋的
     * **/
    @Test
    public void testUpdate(){
        try {
            HttpSolrServer server = getSolrServer();
            server.addBean(new Message("5","id爲5的數據被修改了", "hello,看來我真的被修改了"));
            server.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
    }
    /**
     * 查詢,默認如果需要查看全部結果,需要使用*進行查詢,不過可以在展示和提交的時候和空格進行轉換
     */
    @Test
    public void testQuery(){
        try {
            HttpSolrServer server = getSolrServer();
            String q = "my_content:hello";//q表示查詢的內容
            SolrQuery query = new SolrQuery(q);
            query.setStart(0)
                 .setRows(3);//進行分頁查詢
            query.setHighlight(true).setHighlightSimplePre("<span color='red'>")
                 .setHighlightSimplePost("</span>");//高亮
            
            query.setParam("hl.fl", "my_content");
            //只有將內容存儲後才能進行展示,比如title_content查詢結果就爲空
            //query.setParam("hl.fl", "my_title,my_content");
            QueryResponse resp = server.query(query);
            SolrDocumentList sdList = resp.getResults();
            long totalResults = sdList.getNumFound();//命中的總記錄數
            System.out.println("totalResults-->"+totalResults);
            for(SolrDocument sd:sdList){
                Collection<String> strs =  sd.getFieldNames();
                System.out.println(sd.getFieldValue("my_title"));
                System.out.println(sd.getFieldValue("my_content"));
                Object id = sd.getFieldValue("id");
                if(resp.getHighlighting().get(id)!=null){
                    System.out.println("高亮的結果-->"
                            +resp.getHighlighting().get(id).get("my_content"));
                }
                System.out.println("-------------------------------");
            
            }
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
    }
}

配置說明:

關於schema.xml的配置說明
 (1)如果需要添加mmseg4j對solr的中文分詞支持,添加:
     <!--配置mmsg4j-->
        <fieldtype name="textComplex" class="solr.TextField" positionIncrementGap="100">
            <analyzer>
                <tokenizer class="com.chenlb.mmseg4j.solr.MMSegTokenizerFactory" mode="complex" dicPath="dic"/>
            </analyzer>
        </fieldtype>
        <fieldtype name="textMaxWord" class="solr.TextField" positionIncrementGap="100">
            <analyzer>
                <tokenizer class="com.chenlb.mmseg4j.solr.MMSegTokenizerFactory" mode="max-word" />
            </analyzer>
        </fieldtype>
        <fieldtype name="textSimple" class="solr.TextField" positionIncrementGap="100">
            <analyzer>
                <tokenizer class="com.chenlb.mmseg4j.solr.MMSegTokenizerFactory" mode="simple" dicPath="n:/custom/path/to/my_dic" />
            </analyzer>
        </fieldtype>
 (2)添加自己的查詢字段:
     <field name="my_title" type="string" indexed="true" stored="true"/>
     <field name="my_content" type="string" indexed="true" stored="true"/>
        其中,name:表示要添加的查詢字段
             type:字段的類型,以及在schema.xml中有定義
             indexed:是否索引
             stored:是否存儲
 (3)如果需要同時在title和content中進行查詢,可以添加如下字段:
       <field name="title_content" type="textComplex" indexed="true" stored="false" multiValued="true"/>
      <copyField source="my_title" dest="title_content"/>
      <copyField source="my_content" dest="title_content"/>
      其中:title_content爲新定義的查詢字段,如果需要同時在title和content中進行查詢,那麼就使用這個查詢字段
 (4)設置默認查詢字段,這樣的話就不需要在Query中進行查詢時使用my_title:hello這樣的格式
      將solrconfig.xml中得 <str name="df">text</str>
      修改爲: <str name="df">title_content</str>
      這樣,如果需要查詢內容在標題字段或內容字段出現的結果的時候,只需要在查詢條件中填寫hello就可以了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章