2015.8.13
使用Mysql实现增加索引以实现加快数据搜索
1.增加索引,当你想对某个字段进行like查询或是关联查询时,添加该字段的索引
或是在phpMyAdmin中进行索引设置
ALTER TABLE `ecs_goods` ADD INDEX(`goods_sn`);
2.Sphinx实现索引快速搜索和全文检索
介绍:是一个基于SQL的全文检索引擎,它提供了比数据库更专业的搜索功能,并且sphinx特别为一些脚本语言设置了搜索的API接口,如:php,python等,同时为mysql也设计了一个存储引擎插件
(并在thinkphp中使用)
yum install expat-devel*
cd /mycms/ThinkPHP/Lirary/Vendor/ (thinkphp项目的目录)
tar xzvf coreseek-3.2.14.tar.gz
cd coreseek-3.2.14
cd mmseg-3.2.14
./bootstrap
./configure --prefix=/usr/local/mmseg3
make && make install
cd ..
cd csft-3.2.14
wget -O - http://blog.atime.me/static/resource/sphinxexpr-gcc4.7.patch.gz | gzip -d - | patch -p0(防止下面make中出现ExprEval错误)
或者直接修改src/sphixexpr.cpp文件的1746, 1777和1823行,将三行中的ExprEval改为this->ExprEval参考http://blog.atime.me/note/sphinx-coreseek-summary.html
sh buildconf.sh
./configure --prefix=/usr/local/coreseek --without-unixodbc --with-mmseg --with-mmseg-includes=/usr/local/mmseg3/include/mmseg/ --with-mmseg-libs=/usr/local/mmseg3/lib/ --with-mysql
yum install mysql-devel libxml2-devel expat-devel
)
make && make install
cd ..
cd testpack
配置csft_mysql.conf文件
/usr/local/coreseek/bin/indexer -c etc/csft_mysql.conf --all(成功后将在var/date目录中生成文件)
/usr/local/coreseek/bin/search -c etc/csft_mysql.conf 网络搜索(普通搜索测试)
正常开启搜索服务/usr/local/coreseek/bin/searchd -c etc/csft_mysql.conf(将该搜索服务设为进程服务)
如要停止搜索服务,请使用/usr/local/coreseek/bin/searchd -c etc/csft_mysql.conf --stop
如要已启动服务,要更新索引,请使用/usr/local/coreseek/bin/indexer -c etc/csft_mysql.conf --all --rotate
mysql数据源的配置可参考testpack/etc/csft_mysql.conf文件
vi etc/csft_mysql.conf
在项目控制器中调用该接口
publicfunctionsearch(){
header("Content-type:text/html;charset=UTF-8");
$keyword=$_GET['kw'];
Vendor('Coreseek.api.sphinxapi');//此处为coreseek中sphinxapi.php文件的目录一般为 coreseek-3.2.14.testpack.api.sphinxapi
//$s = new \SphinxClient;
//加载第三方扩展包的文件 文件名不包含class
$db=M();
$spx=new\SphinxClient();
//实例化SphinxClient
$spx->SetServer('127.0.0.1',9312);
//设置ip和端口
$spx->SetConnectTimeout(5);
//设置超时时间
$spx->SetArrayResult(true);
if(strlen($keyword)>=18){
$spx->SetMatchMode(SPH_MATCH_ALL);//如果用户查询字符大于=18个匹配有查询词
}else{
$spx->SetMatchMode(SPH_MATCH_ANY);//匹配查询词中的任意一个
}
//------
/*$limit = 12;//每页要显示的数量
$page = $_GET['page']>1 ? $_GET['page'] : 1;
//GET值不为1 则按1算
//$spx->setLimits(0,12);
$off = ($page-1)*$limit;
$spx->SetLimits( $off, $limit);*/
//设置分页
$spx->SetLimits(0,12);//设置查询出多少条数据
$result=$spx->query("{$keyword}");
//print_r($result);
/*
* 取出matches中的id,组成字符串
*/
$str='';
foreach($result['matches']as$rrs){
$str.=$rrs['id'].',';
}
$ids=rtrim($str,',');
//dump($result['matches']);
//dump($result);
//操作数据库
$sql="SELECT * FROM cms_post where id in ({$ids})";
$stmt=$db->query($sql);
//循环拼接html并返回
$html="";
$x=1;
foreach($stmtas$u=>$j){
$html.="
".$x."";$html.="
".$j['title']."";$html.="
".$j['content']."";$html.="
";$x++;
}
$res['html']=$html;
$this->ajaxReturn($res);
}