温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用Solr索引MySQL数据

发布时间:2021-08-02 16:43:04 来源:亿速云 阅读:303 作者:chen 栏目:云计算

本篇内容主要讲解“如何使用Solr索引MySQL数据”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何使用Solr索引MySQL数据”吧!

这里使用的是mysql测试。

1、先在mysql中建一个表:solr_test

 如何使用Solr索引MySQL数据

2、插入几条测试数据:

如何使用Solr索引MySQL数据

3、用记事本打solrconfig.xml文件,在solrhome文件夹中。E:\solrhome\mycore\conf\solrconfig.xml

(solrhome文件夹是什么,参见:http://www.cnblogs.com/HD/p/3977799.html)

加入这个节点:

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

4、新建一个data-config.xml文件,与solrconfig.xml同一个目录下。内容为

<dataConfig>
    <dataSource type="JdbcDataSource"
              driver="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/test"
              user="root"
              password="root" />
    <document>
        <entity name="solr_test" transformer="DateFormatTransformer"
            query="SELECT id, subject, content, last_update_time FROM solr_test WHERE id >= ${dataimporter.request.id}">
            <field column='last_update_time' dateTimeFormat='yyyy-MM-dd HH:mm:ss' />
        </entity>
    </document></dataConfig>

说明:这里使用了一个${dataimporter.request.id},这个是参数,后面在做数据导入时,会使用到,以此条件为基准读数据。

5、复制解压出的solr jar包solr-dataimporthandler-4.10.0.jar和solr-dataimporthandler-extras-4.10.0.jar到tomcat solr webapp的WEB-INF\lib目录下。

当然,也包括mysql的jdbc jar包:mysql-connector-java-5.1.7-bin.jar

(还有一种方法是在solrconfig.xml中加入lib节点,然后把jar包放到solrhome下,这样可以不在WEB-INF\lib中加入jar包)

6、用记事本打开schema.xml,在在solrhome文件夹中(同第3点)。内容为:

<?xml version="1.0" ?><schema name="my core" version="1.1">

    <fieldtype name="string"  class="solr.StrField" sortMissingLast="true" omitNorms="true"/>
    <fieldType name="long" class="solr.TrieLongField" precisionStep="0" positionIncrementGap="0"/>
    <fieldType name="date" class="solr.TrieDateField" precisionStep="0" positionIncrementGap="0"/>
    <fieldType name="text_cn" class="solr.TextField">
        <analyzer type="index" class="org.wltea.analyzer.lucene.IKAnalyzer" />
        <analyzer type="query" class="org.wltea.analyzer.lucene.IKAnalyzer" />
    </fieldType>
    
    <!-- general -->
    <field name="id" type="string" indexed="true" stored="true" multiValued="false" required="true"/>
    <field name="subject" type="text_cn" indexed="true" stored="true" />
    <field name="content" type="text_cn" indexed="true" stored="true" />
    <field name="last_update_time" type="date" indexed="true" stored="true" />
    <field name="_version_" type="long" indexed="true" stored="true"/>

     <!-- field to use to determine and enforce document uniqueness. -->
     <uniqueKey>id</uniqueKey>

     <!-- field for the QueryParser to use when an explicit fieldname is absent -->
     <defaultSearchField>subject</defaultSearchField>

     <!-- SolrQueryParser configuration: defaultOperator="AND|OR" -->
     <solrQueryParser defaultOperator="OR"/></schema>

7、更新zookeeper集群配置

solrctl instancedir --update  collection1 /opt/cloudera/parcels/CDH/lib/solr/solr_configs 

8、collection1加载新配置信息

http://localhost:8983/solr/admin/collections?action=RELOAD&name=collection1

9、打开solr web:

如何使用Solr索引MySQL数据

说明:

Custom Parameters填入id=1,这是在第4点中设置的参数。

Clean选项,是指是否删除未匹配到的数据。也就是在数据库select结果中没有,而solr索引库中存在,则删除。

也可以使用这个地址直接访问:

http://localhost:8899/solr/mycore/dataimport?command=full-import&clean=true&commit=true&wt=json&indent=true&entity=solr_test&verbose=false&optimize=false&debug=false&id=1

将返回结果:

如何使用Solr索引MySQL数据

配置好后,之后我们只需要使用这个url地址,就可以不段的去导入数据做索引了。(就这么简单)

10、测试查询:

如何使用Solr索引MySQL数据


当然,dataimport可以加入参数命令,让其重新加载data-config.xml

http://localhost:8899/solr/#/mycore/dataimport/command=reload-config

如果在数据库中添加一条数据,但是Solr索引中没有index这条数据,就查不到,所以一般在使用Solr检索数据库里的内容时,都是先插入数据库,再在Solr中index这条数据,使用Solr的模糊查询或是分词功能来检索数据库里的内容。

DIH增量从MYSQL数据库导入数据
已经学会了如何全量导入MySQL的数据,全量导入在数据量大的时候代价非常大,一般来说都会适用增量的方式来导入数据,下面介绍如何增量导入MYSQL数据库中的数据,以及如何设置定时来做。

1)数据库表的更改

前面已经创建好了一个User的表,这里为了能够进行增量导入,需要新增一个字段updateTime,类型为timestamp,默认值为CURRENT_TIMESTAMP。

有了这样一个字段,Solr才能判断增量导入的时候,哪些数据是新的。

因为Solr本身有一个默认值last_index_time,记录最后一次做full import或者是delta import(增量导入)的时间,这个值存储在文件conf目录的dataimport.properties文件中。

2)data-config.xml中必要属性的设置

transformer 格式转化:HTMLStripTransformer 索引中忽略HTML标签

query:查询数据库表符合记录数据

deltaQuery:增量索引查询主键ID  注意这个只能返回ID字段   

deltaImportQuery:增量索引查询导入的数据 

deletedPkQuery:增量索引删除主键ID查询 注意这个只能返回ID字段   

有关“query”,“deltaImportQuery”, “deltaQuery”的解释,引用官网说明,如下所示:
The query gives the data needed to populate fields of the Solr document in full-import
The deltaImportQuery gives the data needed to populate fields when running a delta-import
The deltaQuery gives the primary keys of the current entity which have changes since the last index time

如果需要关联子表查询,可能需要用到parentDeltaQuery

The parentDeltaQuery uses the changed rows of the current table (fetched with deltaQuery) to give the changed rows in theparent table. This is necessary because whenever a row in the child table changes, we need to re-generate the document which has that field.

更多说明看DeltaImportHandler的说明文档。

针对User表,data-config.xml文件的配置内容如下:

如何使用Solr索引MySQL数据

<?xml version="1.0" encoding="UTF-8"?><dataConfig>
    <dataSource type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://127.0.0.1:3306/mybatis" user="root" password="luxx" batchSize="-1" />  <document name="testDoc">
        <entity name="user" pk="id"
                query="select * from user"
                deltaImportQuery="select * from user where id='${dih.delta.id}'"
                deltaQuery="select id from user where updateTime> '${dataimporter.last_index_time}'">            <field column="id" name="id"/>           <field column="userName" name="userName"/>
            <field column="userAge" name="userAge"/>
            <field column="userAddress" name="userAddress"/><field column="updateTime" name="updateTime"/>     </entity>  </document></dataConfig>

增量索引的原理是从数据库中根据deltaQuery指定的SQL语句查询出所有需要增量导入的数据的ID号。

然后根据deltaImportQuery指定的SQL语句返回所有这些ID的数据,即为这次增量导入所要处理的数据。

核心思想是:通过内置变量“${dih.delta.id}”和 “${dataimporter.last_index_time}”来记录本次要索引的id和最近一次索引的时间。

注意:刚新加上的updateTime字段也要在field属性中配置,同时也要在schema.xml文件中配置:

<field name="updateTime" type="date" indexed="true" stored="true" />

如果业务中还有删除操作,可以在数据库中加一个isDeleted字段来表明该条数据是否已经被删除,这时候Solr在更新index的时候,可以根据这个字段来更新哪些已经删除了的记录的索引。

这时候需要在dataConfig.xml中添加:

query="select * from user where isDeleted=0"
deltaImportQuery="select * from user where id='${dih.delta.id}'"
deltaQuery="select id from user where updateTime> '${dataimporter.last_index_time}' and isDeleted=0"
deletedPkQuery="select id from user where isDeleted=1"

这时候Solr进行增量索引的时候,就会删除数据库中isDeleted=1的数据的索引。

测试增量导入

如果User表里有数据,可以先清空以前的测试数据(因为加的updateTime没有值),用我的Mybatis测试程序添加一个User,数据 库会以当前时间赋值给该字段。在Solr中使用Query查询所有没有查询到该值,使用dataimport?command=delta-import 增量导入,再次查询所有就可以查询到刚刚插入到MySQL的值。

设置增量导入为定时执行的任务

可以用Windows计划任务,或者Linux的Cron来定期访问增量导入的连接来完成定时增量导入的功能,这其实也是可以的,而且应该没什么问题。

但是更方便,更加与Solr本身集成度高的是利用其自身的定时增量导入功能。

1、下载apache-solr-dataimportscheduler-1.0.jar放到\solr-webapp\webapp\WEB-INF\lib目录下:
下载地址:http://code.google.com/p/solr-dataimport-scheduler/downloads/list
也可以到百度云盘下载:http://pan.baidu.com/s/1dDw0MRn

注意:apache-solr-dataimportscheduler-1.0.jar有bug,参考:http://www.denghuafeng.com/post-242.html

2、修改solr的WEB-INF目录下面的web.xml文件:
为<web-app>元素添加一个子元素

<listener>
        <listener-class>
    org.apache.solr.handler.dataimport.scheduler.ApplicationListener        </listener-class>
    </listener>

3、新建配置文件dataimport.properties:

在SOLR_HOME\solr目录下面新建一个目录conf(注意不是SOLR_HOME\solr\collection1下面的conf), 然后用解压文件打开apache-solr-dataimportscheduler-1.0.jar文件,将里面的 dataimport.properties文件拷贝过来,进行修改,下面是最终我的自动定时更新配置文件内容:

如何使用Solr索引MySQL数据

#################################################
#                                               #
#       dataimport scheduler properties         #
#                                               #
#################################################

#  to sync or not to sync
#  1 - active; anything else - inactive
syncEnabled=1

#  which cores to schedule
#  in a multi-core environment you can decide which cores you want syncronized
#  leave empty or comment it out if using single-core deployment
#  syncCores=game,resource
syncCores=collection1

#  solr server name or IP address
#  [defaults to localhost if empty]
server=localhost

#  solr server port
#  [defaults to 80 if empty]
port=8983

#  application name/context
#  [defaults to current ServletContextListener's context (app) name]
webapp=solr

#  URLparams [mandatory]
#  remainder of URL
#http://localhost:8983/solr/collection1/dataimport?command=delta-import&clean=false&commit=true
params=/dataimport?command=delta-import&clean=false&commit=true

#  schedule interval
#  number of minutes between two runs
#  [defaults to 30 if empty]
interval=1

#  重做索引的时间间隔,单位分钟,默认7200,即1天; 
#  为空,为0,或者注释掉:表示永不重做索引
# reBuildIndexInterval=2

#  重做索引的参数
reBuildIndexParams=/dataimport?command=full-import&clean=true&commit=true

#  重做索引时间间隔的计时开始时间,第一次真正执行的时间=reBuildIndexBeginTime+reBuildIndexInterval*60*1000;
#  两种格式:2012-04-11 03:10:00 或者  03:10:00,后一种会自动补全日期部分为服务启动时的日期
reBuildIndexBeginTime=03:10:00

这里为了做测试每1分钟就进行一次增量索引,同时disable了full-import全量索引。

4、测试

在数据库中插入一条数据,在Solr Query中查询,刚开始查不到,Solr进行一次增量索引后就可以查询到了。

一般来说要在你的项目中引入Solr需要考虑以下几点:
1、数据更新频率:每天数据增量有多大,及时更新还是定时更新
2、数据总量:数据要保存多长时间
3、一致性要求:期望多长时间内看到更新的数据,最长允许多长时间延迟
4、数据特点:数据源包括哪些,平均单条记录大小
5、业务特点:有哪些排序要求,检索条件
6、资源复用:已有的硬件配置是怎样的,是否有升级计划

到此,相信大家对“如何使用Solr索引MySQL数据”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI