安装 coreseek

coreseek 下载地址:http://www.coreseek.cn/news/7/52/

在百度网盘的 技术资料 > PHP软件 里面有安装包和打模块的安装包

  

1.安装 mmseg

        将coreseek 解压到任意目录 tar xzf coreseek-3.2.14.tar.gz

cd mmseg-3.2.14
./bootstrap
./configure --prefix=/usr/local/mmseg
make && make install


2.安装 coreseek

cd csft-3.2.14/
sh buildconf.sh
./configure --prefix=/usr/local/coreseek --with-mysql=/alidata/server/mysql --with-mmseg=/usr/local/mmseg/ --with-mmseg-includes=/usr/local/mmseg/include/mmseg/ --with-mmseg-libs=/usr/local/mmseg/lib/

make && make install


参考地址:http://www.coreseek.cn/products/products-install/install_on_bsd_linux/


Sphinx的配置

先配置sphinx

将sphinx.conf-min.dist文件复制为csft.conf

cp /usr/local/coreseek/etc/sphinx.conf.dist /usr/local/coreseek/etc/csft.conf

  

详细配置如下:

# article 数据源
source art
{
        type            = mysql
        sql_host        = localhost
        sql_user        = root
        sql_pass        = root
        sql_db          = scriptjc
        sql_port        = 3306
          
        # sql_sock     = /tmp/mysql.sock
          
        sql_query_pre   = set names utf8
        sql_query_pre   = set SESSION query_cache_type = OFF
        sql_query_pre   = replace into sph_art_counter select 1,max(id) from article
          
        sql_query       = select id,title,atime from article where id <= ( select max_art_id from sph_art_counter where id = 1) and del = 0
        # 排序
        sql_attr_uint   = atime
}
  
# article 索引 
index art{
        source      = art
        path        = /usr/local/coreseek/var/data/art
          
        charset_type        = zh_cn.utf-8
        # 词典位置
        charset_dictpath    = /usr/local/mmseg/etc/
}
  
# article 增量数据源
source art_delta : art{
        sql_query_pre   = set names utf8
        sql_query       = select id,title,atime from article where id > ( select max_art_id from sph_art_counter where id = 1) and del = 0
}
  
# article 增量索引
index art_delta : art{
        source      = art_delta
        path        = /usr/local/coreseek/var/data/art_delta
}
  
indexer
{
    mem_limit               = 32M
}
searchd
{
	port			= 9312
	log				= /root/log/coreseek/searchd.log
	query_log		= /root/log/coreseek/query.log
	read_timeout	= 5
	max_children	= 30
	pid_file		= /usr/local/coreseek/var/log/searchd.pid
	max_matches		= 1000
	seamless_rotate	= 1
	preopen_indexes	= 0
	unlink_old		= 1
}

要手动创建searchd.log、query.log、searchd.pid


创建索引命令

        第一次创建索引会有 libmysqlclient.so.18 相关错误,解决方法看下面的“问题”


indexer

        cd /usr/local/coreseek/bin      首先进入文件夹

        -c          指定配置文件

        --all       对所有索引重新编制索引

        --rotate    用于轮换索引,在不停止服务时增加索引

                在没有启动 searchd 时去掉 --rotate, 启动 searchd 服务时,建立索引要加 --rotate

        --merge     合并索引

  

    ./indexer -c /usr/local/coreseek/etc/csft.conf  索引名称  --rotate

./indexer -c /usr/local/coreseek/etc/csft.conf  main  --rotate

    有默认的配置文件 csft.conf 则可省略“ -c 配置文件 ”


修改配置需要重启

        增加新索引要重启服务才能进行搜索,修改配置文件要重新启动后才可生效。


启动search进程

searchd 

cd /usr/local/coreseek/bin

        -c      指定配置文件

        --stop  停止服务

        -p      指定端口


./searchd -c /usr/local/coreseek/etc/csft.conf

        有默认的配置文件 csft.conf 则可省略“ -c 配置文件 ”启动完成后即可调用Api使用php测试


问题

        建立索引时遇到的问题 libmysqlclient.so.18

ln -s /alidata/server/mysql/lib/libmysqlclient.so.18 /usr/lib64/


        用 ./indexer 建立索引时索引文件名称中出现new,需要在建立索引时指定配置文件 


        ./indexer -c  索引配置文件   索引名称

        索引文件位置:/usr/local/coreseek/var/data/索引文件

          


问题2

错误提示:

FATAL: failed to lock pid file '/root/log/searchd.pid': Resource temporarily unavailable (searchd already running?)         // 致命错误:未能锁定PID文件


解决方法:重启服务

./searchd --stop     // 停止服务
./searchd -c /usr/local/coreseek/etc/csft.conf     // 启动服务


参考:http://blog.csdn.net/myweishanli/article/details/42125625



php调用Sphinx

        1.将文件 coreseek-3.2.14/testpack/api/sphinxapi.php 拷贝到任意可被php程序包含出。

        2.在要调用的脚本中包含文件 sphinxapi.php 如下示例

require('./Public/api/sphinxapi.php'); //包含sphinx
class SphinxController extends CommonController{
  public function index(){
     $cl = new \SphinxClient ();
     $cl->SetServer ( '127.0.0.1', 9312);
     $cl->SetConnectTimeout ( 3 );
     $cl->SetArrayResult ( true );
      $cl->SetMatchMode ( SPH_MATCH_ANY);
     $res = $cl->Query ( 'emma', "*" );
     print_r($cl);
     print_r($res);
  }
}

获取错误与警告

if($result === false){
   echo $sphinx->GetLastError();
}
if($sphinx->GetLastWarning()){
   echo $sphinx->GetLastWarning();
}


实时索引

cd /usr/local/coreseek/etc

// 创建自动执行脚本

touch main.sh
chmod 755 main.sh

touch delta.sh
chmod 755 delta.sh

vi main.sh

#!/bin/bash
#main.sh
/usr/local/coreseek/bin/indexer main --rotate >> /usr/local/coreseek/var/log/main.log

vi delta.sh

#!/bin/bash
#delta.sh
/usr/local/coreseek/bin/indexer delta --rotate >> /usr/local/coreseek/var/log/delta.log


添加计划任务


定时任务:

/sbin/service crond start     启动服务
/sbin/service crond stop      关闭服务
/sbin/service crond restar        重启服务
/sbin/service crond reload        重新载入配置


crontab 命令及参数

        -u      设定某个用户的cron服务,一般root用户在执行这个命令的时候需要此参数

        -l      列出某个用户cron服务的详细内容

        -r      删除没个用户的cron服务

        -e      编辑某个用户的cron服务


例:

crontab -e
 */ 15 * * * * /usr/local/coreseek/etc/art_delta.sh
00 03 * * * /usr/local/coreseek/etc/art.sh

  

sphinx内置函数


执行查询

        query( )     执行搜索查询


关键字高亮

buildExcerpts( )         可以高亮显示搜索文字,失败时返回假。成功时返回包含有片段(摘要)字符串的数组。

例:

$sphinx->BuildExcerpts($title,'article',$word,array(
        'before_match'=>'<font class="c_red bold">',
        'after_match'=>'</font>',
        'limit'=>'150',
        'single_passage'=>true,
));

before_match         在匹配的关键字前面插入的字符串。默认为“<b>”

chunk_separator    在摘要块(段落)之间插入的字符串。默认为“...”

limit                        摘要最多包含的符号(码点)数。整数,默认为 256.

around                   每个关键词块左右选取的词的数目。整数,默认为 5,显示的样式为:...x x x x x word x x x x x ...x x x x x word x x x x x ... 这个word为要搜索的关键词,每个匹配到的关键词所在的句子左右都显示5个单词,其他内容不显示。数字越小在字数相同的情况下看到被标红的单词越多。

exact_phrase          是否仅高亮精确匹配的整个查询词组,而不是单独的关键词。布尔值,默认为假。

single_passage       是否仅抽取最佳的一个段落。布尔值,默认为否。


设置匹配模式

setMatchMode        设置全文查询的匹配模式

        SPH_MATCH_ALL              匹配所有查询词(默认模式)

        SPH_MATCH_ANY            匹配查询词中的任意一个

        SPH_MATCH_PHRASE      将整个查询看作一个词组,要求按顺序完整匹配

        SPH_MATCH_BOOLEAN   将查询看作一个布尔表达式 (参见 节 4.2, “布尔查询语法”

        SPH_MATCH_EXTENDED  将查询看作一个 Sphinx 内部查询语言的表达式(参见节 4.3, “扩展的查询语法”)


设置查询时间

        setMaxQueryTime(3)      单位秒,设置最大查询时间,超过这个时间就停止查询


结果分页显示,与限制结果数量

$sp->SetLimits(1,2,3,4);

        1.int 同limit

        2.int 同limit

        3.int 最优匹配数,只返回这么多,实际上匹配了很多,但返回最相关的调用时设置的数,不可超过配置文件的 max_matches 默认为1000

        4.int 匹配数,提高性能用,匹配了这么多就停止


setRankingMode  设置排名模式

        SPH_RANK_PROXIMITY_BM25        默认模式,同时使用词组评分和 BM25 评分,并且将二者结合。

        SPH_RANK_BM25        统计相关度计算模式,仅使用 BM25 评分计算(与大多数全文检索引擎相同)。这个模式比较快,但是可能使包含多个词的查询的结果质量下降。

        SPH_RANK_NONE        禁用评分的模式,这是最快的模式。实际上这种模式与布尔搜索相同。所有的匹配项都被赋予权重 1。


按字段名称设置字段的权值

setFieldWeights(array(
        '字段'=>整数,
        '字段'=>整数
));


设置排序模式

setSortMode( )     设置排序匹配模式

        SPH_SORT_RELEVANCE      按相关度降序(最好的匹配排在最前面)(默认)相当于@weight DESC, @id ASC

        SPH_SORT_ATTR_DESC      按属性降序相当于:attribute DESC, @weight DESC, @id ASC

        SPH_SORT_ATTR_ASC        按属性升序相当于:attribute ASC, @weight DESC, @id ASC

        SPH_SORT_TIME_SEGMENTS      先按时间段降序,再按相关度降序

        SPH_SORT_EXTENDED*      按一种类似 SQL 的方式将列组合起来,升序或降序排列。@weight DESC ,hits DESC

        SPH_SORT_EXPR                 按某个算术表达式排序。

        详见手册4.5排序模式


内部属性:@id(匹配的 ID)    @weight (匹配权值)

$cl->SetSortMode ( SPH_SORT_ATTR_ASC ,'atime');       按时间正序
$cl->SetSortMode ( SPH_SORT_EXTENDED ,'@weight DESC, atime DESC');
$cl->SetSortMode ( SPH_SORT_EXPR, "@weight + ( user_karma + ln(pageviews) )*0.1" );


查询结果

addQuery    多查询批量添加查询

$cl->SetSortMode ( SPH_SORT_RELEVANCE );
$cl->AddQuery ( "hello world", "documents" );
$cl->SetSortMode ( SPH_SORT_ATTR_DESC, "price" );
$cl->AddQuery ( "ipod", "products" );
$cl->AddQuery ( "harry potter", "books" );
$results = $cl->RunQueries ();


更新属性

updateAttributes    立即更新指定文档的指定属性值

$cl->UpdateAttributes (
"索引名", 
    array("字段名1","字段名2",.....), 
    array( 
        字段id =>array(属性值1,属性值2,.....),
        字段id =>array(属性值1,属性值2,.....),
    ....
)
);
$cl->UpdateAttributes (
    "products", 
    array ( "price", "amount_in_stock" ),
    array ( 1001=>array(123,5), 1002=>array(37,11), 1003=>(25,129) ) 
);


限制ID范围

        SetIDRange          限制ID范围

        $cl->SetIdRange(允许最小的ID,允许最大的ID);


设置结果集格式

        setArrayResult      控制搜索结果集的返回格式

        $cl->setArrayResult(false) false时ID为健名,true时ID为健值

        runQueries          运行一个批搜索查询


buildKeywords    从查询中提取关键字

close                    关闭先前打开的持久连接

open                    建立到搜索服务端的持久连接

__construct          创建一个新的SphinxClient对象

  

escapeString        转义特殊字符

getLastError         获取最后一条错误信息

getLastWarning   获取最后一条警告信息

  

resetGroupBy              清除所有group by设置

setConnectTimeout    设置连接超时

  

resetFilters        清除所有过滤器

setFilter             增加整数值过滤器

setFilterFloatRange    添加新的浮动范围过滤器

setFilterRange            添加新的整数范围内过滤器

  

setGeoAnchor        设置锚点岩石圈的距离计算

setGroupBy            设置分组属性

setGroupDistinct    设置属性名称为每个小组的不同值数计算

  

setIndexWeights     设置每重量

setOverride             设置临时每个文档属性值覆盖

setRetries                设置重试计数和延迟

setSelect                 设置select子句

setServer                 设置searchd的主机名和TCP端口

status                      查询searchd状态


 

安装php模块:

        sphinx的php模块下载地址:http://pecl.php.net/package/sphinx

        下载后解压,tar zxf sphinx-1.1.0.tgz,源代码文件有一个错误需要修改,否者编译时会出现错误而编译失败。进入到文件夹 sphinx-1.1.0 找到名为sphinx.c的文件,修改方法如下:

搜索到下面这个行:

/retval = std_hnd->read_property(object, member, type TSRMLS_CC)

将上面这行修改成如下:

retval = std_hnd->read_property(object, member, type TSRMLS_CC, NULL);

修改后保存即可。


编译安装libsphinxclient:

进入下面这个目录:

cd /root/coreseek-3.2.14/csft-3.2.14/api/libsphinxclient
./configure
make && make install


使用phpize生成配置文件:

        sphinx模块文件是没有configure文件的,需要借助phpize生成,切换到sphinx的编译目录,cd sphinx-1.1.0然后在这个目录下运行phpize命令。运行命令/alidata/server/php/bin/phpize,这个命令的位置根据本机php安装的位置找到即可。运行后查看sphinx1.1.0目录,原来的几个文件现在变成很多文件,其中有一个配置文件configure ,然后即可编译安装sphinx模块了。

./configure --with-php-config=/alidata/server/php/bin/php-config --with-sphinx
make && make install


        安装成功后会在最后有一个提示,Installing shared extensions: /alidata/server/php/lib/php/extensions/no-debug-non-zts-20121212/ 这是安装的php模块的位置。


php.ini加载sphinx模块:

        然后在php中加载sphinx模块,修改php的配置文件php.ini,开启这一项:extension=sphinx.so

 

生成索引的shell脚本

主索引

#!/bin/bash
/usr/local/coreseek/bin/indexer art --rotate >> /root/log/sphinx_art.log

增量索引

#!/bin/bash
/usr/local/coreseek/bin/indexer art_delta --rotate >> /root/log/sphinx_art_delta.log


定时任务

0 3 1 * *    /root/shell/sphinx_art.sh
0 2 */2 * *  /root/shell/sphinx_art_delta.sh


为sphinx建立词库或添加新词


词库相关文件

默认情况下sphinx词库放在 /usr/local/mmseg/etc 目录中

-rwxr-xr-x 1 root root     229 May  8 20:21 mmseg.ini
-rwxr-xr-x 1 root root 1826251 May  8 20:21 unigram.txt
-rwxr-xr-x 1 root root 3729280 May  8 20:21 uni.lib

        mmseg.ini 是配置文件,unigram.txt 是词库中包含的词,没什么实际用途,只是用来生成词库的,uni.lib 这个文件是搜索用的词库。

  

生成词库文件方法

我们的目的就是要得到uni.lib库文件

使用如下命令可生成词库uni.lib

/usr/local/mmseg/bin/mmseg -u /usr/local/mmseg/etc/unigram.txt

这样执行结果会生成一个 unigram.txt.uni 文件,需要重命名为 uni.lib 并重建sphin索引即可使用

  

向词文件中添加词

词文件格式如下:

所以不学无术  1
x:1
奸险  1
x:1
楼兰  1
x:1
踏步  1
x:1

添加好后用上面的命令生成词库uni.lib即可。

完成后重新建立索引即可生效。


生成词文件的脚本

$str = <<<EOF
    <form action="" method="post" enctype="multipart/form-data">
    <tr>
        <td><input type="file" name="table1" value=""/></td>
    </tr>
    <tr>
        <td><input type="submit" class="btn" value="下载"/></td>
    </tr>
EOF;
$words = $_FILES['table1']['tmp_name'];
if(is_file($words)){
        header("Content-type: Content-type:application/vnd.ms-excel");
        header("Accept-Ranges: bytes");
        header("Content-Disposition:attachment; filename=words.txt");
        $handle= fopen($words,'r');
        if ($handle) {
              while (($buffer = fgets($handle, 4096)) !== false) {
              $line = trim($buffer,"\r\n\t ");
            echo "$line\t1\r\nx:1\r\n";
          }
          fclose($handle);
        }
}else{
        echo $str;
}