Solr的安裝部署及簡單使用

jopen 8年前發布 | 101K 次閱讀 Solr 搜索引擎

由于demo項目使用的是maven構建,maven倉庫用的是oschina的,此時solr的最新版本是5.4,而oschina中的solrj最新版本是5.3.1,所以我們為了保持一致性,也將下載5.3.1的solr作為演示


一、下載

    首先需要下載solr5.3.1,具體下載此處略。

二、安裝

    1,解壓tomcat(此處使用的是tomcat 7)

    2,解壓solr5.3.1

    3,將 solr-5.3.1\server\solr-webapp 文件夾底下的 webapp 復制到  tomcat  對應目錄底下的 webapps 中,并將文件夾名字改為 solr(自己指定其他的名字也是可以的)

    4,將 solr-5.3.1\server\lib\ext 文件夾底下的lib全部復制到tomcat底下的 solr/WEB-INF/libs/ 中

    5,復制 log4j.properties到tomcat底下solr對應的classes文件夾下(classes需要創建)

    6,復制 solr-5.3.1\server\solr 文件夾到自己指定的目錄,此目錄需要在下一步驟里填寫(也可以不復制,直接引用)

    7,修改tomcat底下的solr對應的web.xml配置文件,找到以下片段

<env-entry>
       <env-entry-name>solr/home</env-entry-name>
       <env-entry-value>/put/your/solr/home/here</env-entry-value>
       <env-entry-type>java.lang.String</env-entry-type>
    </env-entry>

    注:此片段默認是注釋了的,需要解除注釋。

    將 env-entry-value 里的值替換為剛才第5步的路徑。

三、啟動tomcat,查看安裝結果

    http://localhost:8080/solr/

    注:solr下載下來后,也可以使用自帶的命令來啟動,這里是因為需要配合java web項目,才放在tomcat里做演示使用


以上,我們就將solr安裝到tomcat底下,但是仍然沒有和我們的java項目結合起來使用,同時也沒有加入對應的中文分詞。接下來將繼續講下面的部分。


四、添加自定義solr

在剛才定義的 

solr/home

文件夾底下,新建一個文件夾  my_solr,在my_solr目錄中新建core.properties內容為name=mysolr   (solr中的mysolr應用),同時將下載下來的solr-5.3.1解壓文件中的 server/solr 文件夾的復制到my_solr目錄底下

五、配置中文分詞,以mmseg4j為例

    1,下載jar包(mmseg4j-core-1.10.0.jar、mmseg4j-solr-2.3.0.jar),并復制到tomcat底下的 solr/WEB-INF/libs/ 中

    2,配置my_solr文件夾中的schema.xml,在尾部新增

<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="d:/my_dic" />
    </analyzer>
</fieldtype>

    3,重啟tomcat,查看效果

六、java中調用

    1,在上面說的schema.xml中,添加

<field name="content_test" type="textMaxWord" indexed="true" stored="true" multiValued="true"/>

    2,新建測試類

package demo.test;

import org.apache.solr.client.solrj.*;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
/**
 * solr 5.3.0
 * Created by daxiong on 2015/10/23.
 */
public class MySolr {
 
    //solr url
    public static final String URL = "http://localhost:8080/solr";
    //solr應用
    public static final String SERVER = "mysolr";
    //待索引、查詢字段
    public static String[] docs = {"Solr是一個獨立的企業級搜索應用服務器",
                                    "它對外提供類似于Web-service的API接口",
                                    "用戶可以通過http請求",
                                     "向搜索引擎服務器提交一定格式的XML文件生成索引",
                                    "也可以通過Http Get操作提出查找請求",
                                    "并得到XML格式的返回結果"};
 
    public static SolrClient getSolrClient(){
        return new HttpSolrClient(URL+"/"+SERVER);
    }
 
    /**
     * 新建索引
     */
    public static void createIndex(){
        SolrClient client = getSolrClient();
        int i = 0;
        List<SolrInputDocument> docList = new ArrayList<SolrInputDocument>();
        for(String str : docs){
            SolrInputDocument doc = new SolrInputDocument();
            doc.addField("id",i++);
            doc.addField("content_test", str);
            docList.add(doc);
        }
        try {
            client.add(docList);
            client.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };
 
    /**
     * 搜索
     */
    public static void search(){
        SolrClient client = getSolrClient();
        SolrQuery query = new SolrQuery();
        query.setQuery("content_test:搜索");
        QueryResponse response = null;
        try {
            response = client.query(query);
            System.out.println(response.toString());
            System.out.println();
            SolrDocumentList docs = response.getResults();
            System.out.println("文檔個數:" + docs.getNumFound());
            System.out.println("查詢時間:" + response.getQTime());
            for (SolrDocument doc : docs) {
                System.out.println("id: " + doc.getFieldValue("id") + "      content: " + doc.getFieldValue("content_test"));
            }
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        createIndex();
        search();
    }
}

    3,查看執行結果

{responseHeader={status=0,QTime=23,params={q=content_test:搜索,wt=javabin,version=2}},response={numFound=2,start=0,docs=[SolrDocument{id=0, content_test=[Solr是一個獨立的企業級搜索應用服務器], _version_=1522509944966873088}, SolrDocument{id=3, content_test=[向搜索引擎服務器提交一定格式的XML文件生成索引], _version_=1522509945343311874}]}}

文檔個數:2
查詢時間:23
id: 0      content: [Solr是一個獨立的企業級搜索應用服務器]
id: 3      content: [向搜索引擎服務器提交一定格式的XML文件生成索引]


七,與數據庫整合

    我們通常查詢的數據都是在數據庫(或緩存數據庫),這里以mysql作為示例。

    1,進入my_solr/conf目錄中,找到 solrconfig.xml 配置文件,打開,在其中增加如下代碼

<requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler">
    <lst name="defaults">
        <str name="config">data-config.xml</str>
    </lst>
</requestHandler>

這個是用來配置導入數據的配置文件

    2,增加完后,再在同級目錄增加 data-config.xml 文件,文件內容如下

<?xml version="1.0" encoding="UTF-8"?>
<dataConfig>
<dataSource type="demoDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/demo" user="root" password="" batchSize="-1" />
    <document>
        <entity name="t_user" pk="id" query="SELECT * FROM t_user">
            <field column="username" name="username" />
        </entity>
    </document>
</dataConfig>

其中配置的字段請填寫自己數據庫的相應配置。

    3,然后打開 schema.xml ,在其中增加如下代碼

<field name="username" type="string" indexed="true" stored="true" required="true" multiValued="true" />

這里的username和上面的username對應,用作查詢使用。

    4,打開solr管理后臺 http://localhost:8080/solr/#/mysolr ,點擊左側菜單“Dataimport“,默認勾選項即可,點擊”Excute“按鈕,這時會按照剛才的配置導入相應的數據到solr中,執行完成后會出現如下截圖(執行時間可能會比想象的要長一點)


以上,我們就將mysql和solr關聯了起來。接下來,我們可以點擊左側菜單”Query“,在”q“所在的對話框下,輸入對應的搜索關鍵詞,例如:username:張三,然后點擊”Excute Query“按鈕,就可以在右側看到查詢結果

那么怎么在java中調用,得到自己要的查詢結果呢?

現在我知道的是兩種方法:

1,使用http訪問,返回對應的json數據

2,使用SolrQuery調用(上述已有示例代碼)

相應的高級查詢方法,后續如果有時間會繼續補充。

    

來自: http://my.oschina.net/u/238296/blog/597725

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!