Sphinx的安装和使用

一直想搭一个检索的工具,刚好看到用C写的sphinx.之前安装过一阵子,但是一直没搞定。这次决定安装一次。

因为要支持中文切词,安装的方式有两种。
Sphinx + Coreseek和sphinx for Chinese
这里采用偷懒的sphinx for Chinese
一 安装sphinx for Chinese
官方链接: http://sphinxsearchcn.github.io/
1. 下载所需的安装包

2. 解压 tar -zxvf sphinx-for-chinese-0.9.9-r2117.tar.gz

3. 编译安装
$ cd sphinx-for-chinese-0.9.9-r2117.tar.gz
$ ./configure
$ make
$ sudo make install

4. 指定sphinx配置文件
$ cd /usr/local/etc
$ cp sphinx.conf.dist sphinx.conf

5. 编辑该配置文件
vi sphinx.conf
改动内容如下:
sql_host = localhost
sql_user = root
sql_pass = xxxxx
sql_db = your db
sql_port = 3306 # optional, default is 3306
说明:加粗部分是修改的内容

二 安装中文切词
到这里为止,sphinx已经可以使用了,但还不能支持中文切词,以下是加入中文切词的步骤
1. 解压字典文件 xdict_1.1.tar.gz

$ tar zxvf xdict_1.1.tar.gz
2. 借助先前安装的 mkdict 工具生成字典

$ /usr/local/sphinx/bin/mkdict xdict.txt xdict
3. 将字典 xdict 拷贝到 /usr/local/sphinx/etc目录下

4. 配置中文切词
打开 sphinx.conf文件,找到 ‘charset_type = sbcs’ 字样,将其改为:

charset_type = utf-8
chinese_dictionary = /usr/local/sphinx/etc/xdict
至此中文切词配置完成,下面做一个简单的测试
三 简单测试

1. 编辑sphinx-for-chinese自带的SQL脚本,加入中文数据
$ vi /usr/local/sphinx/etc/example.sql

REPLACE INTO test.documents ( id, group_id, group_id2, date_added, title, content ) VALUES
( 1, 1, 5, NOW(), ‘test one’, ‘this is my test document number one. also checking search within phrases.’ ),
( 2, 1, 6, NOW(), ‘test two’, ‘this is my test document number two’ ),
( 3, 2, 7, NOW(), ‘another doc’, ‘this is another group’ ),
( 4, 2, 8, NOW(), ‘doc number four’, ‘this is to test groups’ ),
( 5, 2, 8, NOW(), ‘doc number five’, ‘一个’ ),
( 6, 2, 8, NOW(), ‘doc number six’, ‘我’ ),
( 7, 2, 8, NOW(), ‘doc number seven’, ‘中国人’ );
说明:加粗部分是添加的中文测试数据

2. 导入数据

$ mysql -usphinx -psphinx < example.sql

3. 建立索引

$ sudo /usr/local/sphinx/bin/indexer –all –rotate
如果出以下错误:就给他建 一个
FATAL: failed to open /var/data/test1.spl: No such file or directory
2011-03-26 09:03
FATAL: failed to open /var/data/test1.spl: No such file or directory, will not index. Try –rotate option.

Thats not trying to read that file, but rather create it.
Does /var/data/ folder exist, and is it writable?
mkdir data
http://sphinxsearch.com/forum/view.html?id=3511

4. 检索
$ /usr/local/sphinx/bin/search 测试

words:
‘测试’: 30 documents, 187 hits
四 安装php扩展
1, 到官网http://pecl.php.net/package/sphinx下载最新的扩展
2, 安装安装扩展的步骤,
2.1 phpize
2.2 ./configure –with-php-config=/your/dir/php-config
2.3 make & make install
2.4 修改php.ini并重启
[sphinx]
extension=sphinx.so
3,测试php扩展

        $s = new SphinxClient;
        $s-&gt;setServer(&quot;localhost&quot;, 9312);
        $s-&gt;setMatchMode(SPH_MATCH_ANY);
        $s-&gt;setMaxQueryTime(3);
        $result = $s-&gt;query(&quot;海淀的山后真有可能取代中关村&quot;);
        var_dump($result);

最后遇到一个坑,php7安装sphinx扩展失败!害得我把环境重新装为php5.6,所以现在看到的所有应用都基于php5.6.不过之前有写过两个环境共存的情况,也是非常方便。