Apache Solr配置

來源:互聯網
上載者:User

標籤:Lucene   blog   http   io   ar   os   使用   sp   for   

Solr配置

Solr的主要功能是全文檢索索引,該功能分為兩個過程:建立索引和對索引進行搜尋;在建立索引之前,需要重點關注兩個設定檔:SOLR_HOME/collection1/conf/schema.xml(定義Document的結構類似定義DB的表結構) & solrconfig.xml(solr回合組態如請求如何被處理);在Solr建立索引的過程中,每條資料被抽象成一個Document(文檔),每條資料的屬性被抽象成Field(欄位),Solr原生支援XML,JSON,CSV格式的Document檔案對Document進行添加,刪除;但現實情況是很多應用的資料都儲存在關係型資料庫或者XML檔案中,要想對這些資料進行索引需要通過Data Import Request Handler(Solr擴充模組),該模組提供全量索引(將全部資料進行索引)和增量索引(只對某個時間點之後的資料進行索引)功能;下面筆者將通過一個對MySQL資料庫中資料進行索引的例子來闡述整個過程;1,對資料表topic中的資料建立索引,topic表結構如下:CREATE TABLE `topic` (
  `id` INT(8) NOT NULL AUTO_INCREMENT COMMENT ‘自增id‘,
  `title` VARCHAR(50) DEFAULT NULL COMMENT ‘標題‘,
  `content` TEXT COMMENT ‘內容‘,
  `create_date` BIGINT(15) DEFAULT NULL COMMENT ‘建立時間‘,
  `update_date` BIGINT(15) DEFAULT NULL COMMENT ‘更新時間‘,
  PRIMARY KEY (`id`),
) ENGINE=INNODB CHARSET=utf8全文檢索索引只針對title,content欄位進行其他欄位只做顯示;2,定義Document(文檔)結構,對SOLR_HOME/collection1/conf/schema.xml進行如下修改:在<fields>中添加如下field定義:<!-- 定義文檔Field對應於topic表欄位--><field name="test_id" type="string" indexed="true" stored="true" required="true" multiValued="false" />   <field name="test_title" type="text_chinese_IK" indexed="true" stored="true" /><field name="test_content" type="text_chinese_IK" indexed="true" stored="true" /><field name="test_create_date" type="long" indexed="false" stored="true" /><field name="test_update_date" type="long" indexed="false" stored="true" />field屬性說明:name:必須,field名稱type:必須,field類型名稱,在<types>中通過fieldType定義indexed:true表示該field需要被索引(能搜尋和排序)stored:true表示在索引中儲存該field可在後面被讀取multiValued:true表示該field在文檔中存在多個值required:field是否必須有值,如果索引過程中該field為空白則出錯default:預設值增加fieldType定義,因為要支援中文檢索,建索引時需要使用中文分詞包,筆者使用的是IK Analyzer,下載IK Analyzer 2012FF_hf1版本能支援Solr4,上述配置中使用了type="text_chinese_IK" fieldType,該fieldType並非Solr預定義類型,故需要在<types>中添加該類型的定義並支援中文分詞,定義如下:<fieldType name="text_chinese_IK" class="solr.TextField">
     <analyzer type="index" isMaxWordLength="false" class="org.wltea.analyzer.lucene.IKAnalyzer" />
     <analyzer type="query" isMaxWordLength="true" class="org.wltea.analyzer.lucene.IKAnalyzer" /></fieldType>org.wltea.analyzer.lucene.IKAnalyzer為中文分詞類同時用於索引和搜尋過程,在這裡需要將IK Analyzer中的IKAnalyzer2012FF_u1.jar,stopword.txt,IKAnalyzer.cfg檔案複製到TOMCAT_HOME/webapp/solr/WEB-INF/lib下面設定uniqueKey,每個文檔可通過uniqueKey進行定位,Solr保證一個uniqueKey只存在一個Document:<uniqueKey>test_id</uniqueKey>(作為uniqueKey的field必須是required)3,添加dataimporter處理器,Solr REST風格的APIs保證所有的功能都可通過HTTP請求實現,如查詢/select,索引更新/update等以上功能已在Solr上預定義,dataimporter屬於擴充功能,需要在SOLR_HOME/collection1/conf/solrconfig.xml中添加Data Import Request Handler,如本例:<requestHandler name="/dataimport" class="org.apache.solr.handler.dataimport.DataImportHandler">
    <lst name="defaults">
      <str name="config">./data-config.xml</str>
    </lst>
</requestHandler>org.apache.solr.handler.dataimport.DataImportHandler為DataImporter處理器(擴充模組),需要將Solr-4.2.0/dist/solr-dataimporthandler-4.2.0.jar,solr-dataimporthandler-extras-4.2.0.jar複製到TOMCAT_HOME/webapps/solr/WEB-INF/lib中,data-config.xml為資料來源設定檔,DataImporter使用該檔案從資料來源中讀取資料4,配置data-config.xml,本例從MySQL表topic中匯入資料:<dataConfig>
  <dataSource type="JdbcDataSource"
              batchSize="-1"
              driver="com.mysql.jdbc.Driver"
              url="jdbc:mysql://127.0.0.1:3306/test"
              user="reader"
              password="reader"/>
  <document>
    <entity name="topic" pk="id" onError="Skip" transformer="com.zj.transformer.MySolrTransformer"        query="select id,title,content,create_date,update_date from topic"
        deltaImportQuery="select id,title,content,create_date,update_date from topic where id=${dataimporter.delta.id}"        deltaQuery="select id from topic where update_date>‘${dataimporter.last_index_time}‘">
        <field column="id" name="test_id" />
        <field column="title" name="test_title" />
        <field column="content" name="test_content" />
        <field column="create_date" name="test_create_date" />        <field column="update_date" name="test_update_date" />    </entity>
  </document>
</dataConfig><dataSource>用於定義資料來源,本例定義JdbcDataSource作為資料來源<entity>定義抽取,轉換並將資料添加進索引,name為名稱,pk為主鍵,onError定義出錯處理方式(abort|skip|continue),transformer用於資料轉換(query執行後,添加進索引前),query定義全量索引時資料查詢SQL,deltaImportQuery定義增量索引時資料查詢SQL,deltaQuery定義哪些資料需要增量索引的查詢SQL<field>定義將資料庫列對於到Solr的索引欄位,column為資料庫表欄位名,name為Solr定義的索引欄位名本例中query="select id,title,content,create_date,update_date from topic",全量索引將topic表中的所有資料都添加到Solr索引中,在全量索引完成之後,Solr會自動產生dataimport.properties儲存最近一次索引開始時間戳last_index_time,通過配置deltaImportQuery="select id,title,content,create_date,update_date from topic where id=${dataimporter.delta.id}",deltaQuery="select id from topic where update_date>‘${dataimporter.last_index_time}‘",增量索引將topic中update_date大於last_index_time的資料添加進索引實現累加式更新(註:${dataimporter.delta.id},${dataimporter.last_index_time}是固定寫法除id需要跟deltaQuery="select id ..."對應外其他不可更改要不然DataImporter取不到相應的值);本例的com.zj.transformer.MySolrTransformer主要是為了介紹transformer,並無特殊目的:package com.zj.transformer;public class MySolrTransformer {    public Object transformRow(Map<String, Object> row) {        // row中儲存資料庫查詢出的一條記錄<column_name, value>        // 可以對row進行各種修改        return row;    }}transformer的定製非常簡單完全是無侵入式的,只需要實現public Object transformRow(Map<String, Object> row)方法即可5,啟動索引過程建全量索引,在瀏覽器中輸入:http://ip:port/solr/dataimport?command=full-import&commit=true建增量索引:http://ip:port/solr/dataimport?command=delta-import&clean=false&commit=true(也可通過定時器定時發送HTTP請求建增量索引);6,查詢索引1,直接通過Solr查詢頁面查詢:http://ip:port/solr/#/collection1/query2,通過Solrj API進行查詢:將Solr-4.2.0/dist/solr-solrj-4.2.0.jar,Solr-4.2.0/dist/solrj-lib/httpclient-4.2.3.jar,httpcore-4.2.2.jar,httpmime-4.2.3.jar Copy到工程的classpath中,建立如下代碼:package com.mobcent.searcher.solr.searcher; import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.SolrServer;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.SolrDocumentList; public class CopyOfSolrSearcher {       public static void main(String[] args) {        SolrServer server = new HttpSolrServer("http://127.0.0.1:8080/solr" );        ((HttpSolrServer) server).setSoTimeout(3000);        ((HttpSolrServer) server).setConnectionTimeout(3000);        ((HttpSolrServer) server).setMaxTotalConnections(100);        ((HttpSolrServer) server).setDefaultMaxConnectionsPerHost(100);               SolrQuery query = new SolrQuery();        //set keyword        query.setQuery( "keyword" );        //set filter.        query.addFilterQuery( "field:value" );        //set form to.        //起始頁        query.setStart(0);        //每頁        query.setRows(10);               QueryResponse queryResponse;        try {            queryResponse = server.query(query);            SolrDocumentList docList = queryResponse.getResults();            if (null != docList)                System. out .println("Find Total: " + docList.getNumFound());        } catch (SolrServerException e) {            e.printStackTrace();        }    }}總結,以上通過一個具體的例子對Solr進行配置,走完了使用Solr的整個流程,建立索引,對索引進行搜尋;順便說一句,Solr的Wiki是個不錯的學習Solr的好地方;Apache SolrCloud介紹及安裝 | Apache Solr介紹及安裝 

Apache Solr配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.