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的好地方;

Apache Solr配置的更多相关文章

  1. 05 Apache Solr: 管理员界面(Admin UI)

         为了方便管理员和工程师调整Solr的配置和访问在线文档和其他的帮助,Solr提供了一个Web界面去查看Solr的配置详情,运行查询语句和分析文档字段.这个界面在第三篇里面提到过就是管理员界面 ...

  2. 03 Apache Solr: 安装和运行

         前面介绍了Solr在项目中的使用和构建高度可用.高度可扩展的Solr服务器的一些想法.但是光说不练假把式,现在开始,把Solr运行起来继续深入了解吧! 安装 安装JAVA Apache So ...

  3. 02 Apache Solr: 概览 Solr在信息系统架构中的位置

    概述:      Apache Solr是一个用JAVA语言构建在Apache Lucene项目上的开源的企业级搜索平台.主要特性包含:全文搜索.命中高亮.片段式搜索.实时索引.动态集群.数据库集成. ...

  4. Apache Solr查询语法(转)

    查询参数 常用: q - 查询字符串,必须的. fl - 指定返回那些字段内容,用逗号或空格分隔多个. start - 返回第一条记录在完整找到结果中的偏移位置,0开始,一般分页用. rows - 指 ...

  5. Apache Solr查询语法

    常用: q - 查询字符串,必须的. fl - 指定返回那些字段内容,用逗号或空格分隔多个. start - 返回第一条记录在完整找到结果中的偏移位置,0开始,一般分页用. rows - 指定返回结果 ...

  6. solrj:org.apache.solr.common.util.NamedList.java

    package org.apache.solr.common.util; import java.io.Serializable; import java.util.ArrayList; import ...

  7. Apache Solr采用Java开发、基于Lucene的全文搜索服务器

    http://docs.spring.io/spring-data/solr/ 首先介绍一下solr: Apache Solr (读音: SOLer) 是一个开源.高性能.采用Java开发.基于Luc ...

  8. Solr配置与简单Demo

    简介: solr是基于Lucene Java搜索库的企业级全文搜索引擎,目前是apache的一个项目.它的官方网址在http://lucene.apache.org/solr/  .solr需要运行在 ...

  9. Solr配置与简单Demo[转]

    Solr配置与简单Demo 简介: solr是基于Lucene Java搜索库的企业级全文搜索引擎,目前是apache的一个项目.它的官方网址在http://lucene.apache.org/sol ...

随机推荐

  1. 和阿木聊Node.js

    npm:node.js官方库 cnpm:taobao维护的库: WebStorm:Node.js的开发工具,但是收费: seajs:还有一款交requirjs,前者是遵循amd规范(一次性参数中加载要 ...

  2. CoreGraphics --- 翻转坐标系

    1. 由于CoreGraphics 的坐标系与手机屏幕坐标系的Y轴是相反的, 所以在我们开发的时候, 需要翻转坐标系; - (void)drawRect:(CGRect)rect { CGContex ...

  3. XCode 项目配置说明

    初学XCode最让人头疼的就是项目各属性设置,各种不解,这里做个总结: 项目配置: 基本项(Basic) 1.Architectures(指令集)——设置你想支持的指令集,目前ios的指令集有以下几种 ...

  4. Java多线程初学者指南(12):使用Synchronized块同步变量

    我们可以通过synchronized块来同步特定的静态或非静态方法.要想实现这种需求必须为这些特性的方法定义一个类变量,然后将这些方法的代码用synchronized块括起来,并将这个类变量作为参数传 ...

  5. Android 联系人信息的读取注意判断是否为NULL Android联系人的删除实质

    在Android系统联系人界面删除一条短信实际上并不是真正的删除,而是在数据库中标记raw_contacts表中Contact_id为null以及data表中raw_contact_id为空,这是为了 ...

  6. 李洪强iOS开发之-cocopods安装

  7. 李洪强iOS开发Swift篇—10_方法

    李洪强iOS开发Swift篇—10_方法 一.简单说明 跟其他面向对象语言一样,Swift中的方法可以分为2大类: (1)实例方法(Instance Methods) 在OC中,实例方法以减号(-)开 ...

  8. [wikioi]最优布线问题

    http://wikioi.com/problem/1231/ Kruskal+并查集.comp函数里面如果用const引用的话,可以减少copy.并查集find的时候是递归找父亲的根.无他. #in ...

  9. spring初始化

    * Created by litao on 15/12/29. */@Component("initTagDataProcessor")public class InitTagDa ...

  10. [LeetCode] Burst Balloons (Medium)

    Burst Balloons (Medium) 这题没有做出来. 自己的思路停留在暴力的解法, 时间复杂度很高: 初始化maxCount = 0. 对于当前长度为k的数组nums, 从0到k - 1逐 ...