`
warm_breeze
  • 浏览: 61718 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Apache Solr配置

    博客分类:
  • Solr
阅读更多

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/query
2,通过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的好地方;
3
3
分享到:
评论
1 楼 xzcgeorge 2013-06-17  
 

相关推荐

Global site tag (gtag.js) - Google Analytics