注:sphinx的增量索引其实是通过两个索引来实现的(主索引每天凌晨更新,增量索引每5分钟生成一次),网上有说可以通过索引merge合并成一个索引,但我试了试没有真的合并进去
sphinx 增量索引的设置
数据库中的已有数据很大,又不断有新数据加入到数据库中,也希望能够检索到。全部重新建立索引很消耗资源,因为我们需要更新的数据相比较而言很少。
例如。原来的数据有几百万条,而新增的只是几千条。这样就可以使用“主索引+增量索引”的模式来实现近乎实时更新的功能。
这
个模式实现的基本原理是设置两个数据源和两个索引,为那些基本不更新的数据建立主索引,而对于那些新
增的数据建立增量索引。主索引的更新频率可以设置的长一些(例如设置在每天的午夜进行),而增量索引的更新频率,我们可以将时间设置的很短(几分钟左
右),这样在用户搜索的时候,我们可以同时查询这两个索引的数据。
使用“主索引+增量索引”方法有个简单的实现,在数据库中增加一个计数表,记录每次重新构建主索引时,被索引表的最后一个数据id,这样在增量索引时只需要索引这个id以后的数据即可,每次重新构建主索引时都更新这个表。
测试条件:以默认的sphinx.conf配置为例,数据库表的数据也以 example.sql为例。
1、创建相关表
创建主索引表
create table `sph_test1` (
`id` int(10) unsigned not null,
`weight` int(11) not null,
`query` varchar(3072) character set latin1 not null,
`group_id` int(11) default null,
key `query` (`query`)
) engine=sphinx default charset=utf8 connection='sphinx://127.0.0.1:9312/test1'
创建索引计数表
create table `sph_counter` (
`id` int(11) not null,
`max_doc_id` int(11) not null,
primary key (`id`)
)
创建增量索引表
create table `sph_delta_test1` (
`id` int(10) unsigned not null,
`weight` int(11) not null,
`query` varchar(3072) not null,
`group_id` int(11) default null,
key `query` (`query`(1024))
) engine=sphinx default charset=utf8 connection='sphinx://127.0.0.1:9312/delta_test1'
2、修改sphinx.conf
source src1{
type = mysql
sql_host = localhost
sql_user = yourusername
sql_pass = yourpassword
sql_db = test //你所用的数据库
sql_port = 3306 //所用端口,默认是3306
sql_query_pre = set names utf8
sql_query_pre = sql_query_pre = replace into sph_counter select 1, max(id) from documents
sql_query = select id, group_id, unix_timestamp(date_added) as date_added, title,\
content from documents \
where id( select max_doc_id from sph_counter where counter_id=1 )
}
index test1 //主索引{
source = src1
path = /usr/local/sphinx/var/data/test1
charset_type = utf-8 #这个是支持中文必须要设置的
chinese_dictionary =/usr/local/sphinx/etc/xdict #..........其它可以默认
}
index delta_test1: src1 //增量索引{
source = delta_src1
path = /usr/local/sphinx/var/data/delta_src1
}
3、定时任务生成索引(--rotate 参数可以不重启服务索引就能生效)
a、每天凌晨生成全量索引:./indexer test1 --rotate
b、每10分钟生成一次增量索引 :./indexer delta_test1 --rotate