sphinx全文搜索的安装、使用

1.下载最新版sphinx      wget http://sphinxsearch.com/files/sphinx-2.2.9-release.tar.gz

2.解压       tar -xvf sphinx-2.2.9-release.tar.gz

3.运行configure脚本      ./configure –prefix=/usr/lcoal/sphinx

sphinx configure

sphinx configure

4.编译和安装      make && make install

sphinx make & make install

sphinx make & make install

5.复制安装目录/usr/local/sphinx/sphinx.conf.dist模板到/usr/local/sphinx/etc/sphinx.conf   cp /usr/local/sphinx/sphinx.conf.dist   /usr/local/sphinx/etc/sphinx.conf

6.编辑sphinx.conf配置sphinx   vim /usr/local/sphinx/etc/sphinx.conf

重要:
取消注释ngram_len = 1 此处设置:简单分词,只支持0和1,默认为0,如果要搜索中文,置为1
取消注释ngram_chars = U+3000..U+2FA1F 此处设置:需要分词的字符,如果要搜索中文,去掉前面的注释
如果没有分布式索引需要注释index dist1段

sphinx.conf配置

sphinx.conf配置

7.建立sphinx索引   /usr/local/sphinx/bin/indexer –all
如果sphinx已经启动了的话加上–rotate选项,当然可以把/usr/local/sphinx/bin加入PATH环境变量中,就不需要那么长的路径了

indexer error

indexer error

建立索引时报错了,sphinx没法连接mysql。错误很明显,找不到mysql.sock

查找mysql.sock的位置,并编辑sphinx.conf把/var/lib/mysql/mysql.sock改成自己的位置,我的事/tmp/mysql.sock

mysql.sock location

mysql.sock location

再次运行 /usr/local/sphinx/bin/indexer –all –rotate

indexer --all --rotate

indexer –all –rotate

sphinx全文索引建立成功

8.启动sphinx服务     ./searchd

启动sphinx

启动sphinx

sphinx安装、配置、启动完毕。接下来就是客户端,客户端语言sphinx提供了rubby java php python等的接口,不过即使没有提供sdk,自己慢慢去写socket交互,这个就对能力要求有些高咯

老规矩,我是个phper,虽然会一丢丢c、java、python,不过,还是php最拿的出手,就用php咯

代码测试地址:http://blog.feehi.com/sphinx.php

PS:sphinxapi.php在第一步下载来的文件中,解压后,在api目录下能找到各个语言的sdk

<?php
error_reporting(0);
if($_GET['k']){
require 'sphinxapi.php';
$s = new SphinxClient();
$s->SetServer('localhost',9312);
$k = $_GET['k'];
$result = $s->Query($k);
//var_dump($result);die;
$ids = '';
$i = 0;
if( count($result['matches']) > 0 ){
foreach($result['matches'] as $key => $value){
if($value["attrs"]['status'] != 'publish') continue;
if($i==0)
$ids = $key;
else
$ids .= ','.$key;
$i++;
}
$pdo = new PDO('mysql:host=localhost;dbname=blog', 'root', '密马赛克码');
$pdo -> query('set names utf8');
$res = $pdo -> query("select id,post_title,post_content from blog_posts where id in($ids)");
$info = $res -> fetchAll();
//var_dump($info);die;
foreach($info as $kk => $vv){
echo "<a target='_blank' href='http://blog.feehi.com/?p=".$vv['id']."'>{$vv['post_title']}</a><br>";
}
}else{
echo('本搜索采用的是sphinx全文搜索,木有找到您要的结果,请更换关键字搜索.');
}
}
?>
<form action='/sphinx.php'>
<input type='text' name='k'/>
<input type='submit' value='sphinx全文搜索'/>
</form>

sphinx实时搜索好像是最新版本中增加的,如果对于实时性要求没那么高的话,设置一下crond,让sphinx在每天夜深人静的时候自动更新索引
00 00 * * * /usr/local/sphinx/bin/indexer –all –rotate

点击进入本博客sphinx搜索地址》》》

sphinx

sphinx

 

评论

目前评论:0   

点击加载更多评