【整理】Linux下中文檢索引擎coreseek4安裝,以及PHP使用sphinx的三種方式(sphinxapi,sphinx的php擴充,SphinxSe作為mysql儲存引擎)

來源:互聯網
上載者:User

標籤:comm   1.3   ted   toolbar   group   寫法   count   aclocal   權重   

     
一,軟體準備
  1. coreseek4.1 (包含coreseek測試版和mmseg最新版本,以及測試資料包【內建中文分詞與搜尋、單字切分、mysql資料來源、python資料來源、RT即時索引等測試組態】) 
  2. Mysql源碼包 (必須選擇與你已安裝mysql的版本一致)

  為了避免安裝中出現依賴包缺失,你需要打一句雞血:

yum install make gcc g++ gcc-c++ libtool autoconf automake imake mysql-devel libxml2-devel expat-devel#或apt-get install make gcc g++ automake libtool mysql-client libmysqlclient15-dev libxml2-dev libexpat1-dev#更多系統配置請點此傳送查看

 

二,coreseek快速安裝
1,安裝mmseg3
##前提:需提前安裝作業系統基礎開發庫及mysql依賴庫以支援mysql資料來源和xml資料來源##安裝mmseg$ cd mmseg-3.2.14$ ./bootstrap    #輸出的warning資訊可以忽略,如果出現error則需要解決$ ./configure --prefix=/usr/local/mmseg3 $ make && make install$ cd ..

【注意】如果編譯mmseg提示cannot find input file: src/Makefile.in失敗,可以嘗試下面解決方案:

#下面命令提示沒有安裝,則先安裝aclocallibtoolize --force 運行後有一個錯誤,不用管它。automake --add-missingautoconfautoheadermake clean./configure --prefix=/usr/local/mmseg3

 

 2,安裝coreseek
##安裝coreseek$ cd csft-4.1$ sh buildconf.sh    #輸出的warning資訊可以忽略,如果出現error則需要解決$ ./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    ##如果提示mysql問題,可以查看MySQL資料來源安裝說明#不想麻煩,可以直接使用下面這句$ ./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-includes=《mysql安裝目錄》/include --with-mysql-libs=《mysql安裝目錄》/lib
$ make && make install$ cd ..

【注意】如果出現Sphinx/Coreseek 4.1 執行 buildconf.sh 報錯,無法產生configure檔案的問題,點此傳送解決。值得一提的是vi‘替換所有’小技巧:末行模式下輸入“:1,$s/T val = ExprEval ( this->m_pArg, tMatch )/T val = this->ExprEval ( this->m_pArg, tMatch )/g”從第一行開始替換到最後一行

 

3,測試mmseg分詞,coreseek搜尋
##測試mmseg分詞,coreseek搜尋(需要預先設定好字元集為zh_CN.UTF-8,確保正確顯示中文)$ cd testpack$ cat var/test/test.xml    #此時應該正確顯示中文$ /usr/local/mmseg3/bin/mmseg -d /usr/local/mmseg3/etc var/test/test.xml$ /usr/local/coreseek/bin/indexer -c etc/csft.conf --all$ /usr/local/coreseek/bin/search -c etc/csft.conf 網路搜尋

【注意】 

  1,如果輸入/usr/local/coreseek/bin/indexer -c etc/csft.conf --all 時報/usr/local/coreseek/bin/indexer: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object file: No such file or directory 錯誤,可以通過vi編輯 /etc/ld.so.conf檔案來修複這個錯,將 /usr/local/MySQL/lib  加到檔案到尾部,並儲存檔案,然後運行ldconfig命令即可。

  2,如果輸入/usr/local/coreseek/bin/indexer -c etc/csft.conf --all,報xmlpipe2 support NOT compiled in. To use xmlpipe2, install missing錯誤,則apt-get install expat-* 或yum install expat-devel*安裝後重新編輯安裝coreseek。

 

三,Sphinx配置mysql資料來源:
  1,首先,要搞清楚coreseek的bin目錄下的 三個主要檔案是幹嘛的:
  1./usr/local/coreseek/bin/indexer indexer檔案,用於建立/更新/合并資料來源的索引
   /usr/local/coreseek/bin/indexer -c etc/csft_mysql.conf --all 為csft_mysql.conf設定檔中配置的所有資料來源建立索引
  2./usr/local/coreseek/bin/search search檔案,用於測試資料來源的搜尋   /usr/local/coreseek/bin/search -c etc/csft_mysql.conf 網路搜尋 測試csft_mysql.conf設定檔中配置的資料來源是否有“網路搜尋”這個內容
  3./usr/local/coreseek/bin/searchd searchd檔案,負責接受查詢、處理查詢和返回資料集的服務   /usr/local/coreseek/bin/searchd -c etc/csft_mysql.conf 通過csft_mysql.conf的searchd配置開啟負責接受查詢、處理查詢和返回資料集的服務
     2,再者,搞清楚我們要為mysql中的某個資料庫中哪(幾)個表建立索引。
  下面以一個案例作為例子講解:  一個線上聊天項目,使用了資料庫test_qq,以say作為儲存聊天內容表,此項目有一個“尋找聊天記錄”的功能,此表內容基本會達到海量的,因此為了提高尋找速度,為表say建立索引(sphinx的資料來源),表say有如下結構:
mysql> use test_qq;Database changedmysql> desc say;+---------+------------------+------+-----+---------+----------------+| Field   | Type             | Null | Key | Default | Extra          |+---------+------------------+------+-----+---------+----------------+| id      | int(10) unsigned | NO   | PRI | NULL    | auto_increment || fromid  | int(10) unsigned | NO   |     | 0       |                || toid    | int(10) unsigned | NO   |     | 0       |                || content | text             | NO   |     | NULL    |                |+---------+------------------+------+-----+---------+----------------+
要配置mysql資料來源,我們將coreseek安裝包/testpack/etc 下的csft_mysql.conf檔案複製到coreseek 的etc目錄中:
cp /coreseek安裝包位置/testpack/etc/csft_mysql.conf /usr/local/coreseek/etc/
修改csft_mysql.conf
 View Code
修改後,先開啟searchd後台服務
/usr/local/coreseek/bin/searchd -c /usr/local/coreseek/etc/csft_mysql.conf再執行整體索引
/usr/local/coreseek/bin/indexer -c /usr/local/coreseek/etc/csft_mysql.conf --all此時便可以使用search 來測試搜尋
/usr/local/coreseek/bin/search -c /usr/local/coreseek/etc/csft_mysql.conf 你好得出搜尋結果,即為配置成功但是問題來了,indexer索引是一次性的,如果是10:00am執行索引,search就只能搜尋到10:00am以前的內容,那如果更多的人在10:00am後發訊息,say表中多出的聊天內容行就無法被索引到,search測試也就無法搜尋到多出的內容,我們就考慮到增量索引。?配置增量索引:  1.在mysql中建立索引記錄位移表sph_say_counter,當執行一次索引後,sph_say_counter表更新該次索引最大id,等下次執行索引時,便從該記錄的最大id開始執行索引,執行後再將該次索引最大id記錄到sph_say_counter中。如此重複。

    sph_say_counter表結構:

mysql> desc sph_say_counter;+------------+---------------------+------+-----+---------+----------------+| Field      | Type                | Null | Key | Default | Extra          |+------------+---------------------+------+-----+---------+----------------+| id         | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment || max_offset | int(10) unsigned    | NO   |     | 0       |                |+------------+---------------------+------+-----+---------+----------------+

  2. 在csft_mysql.conf增加增量索引配置

#增加以下配置source delta : mysql #此寫法為delta繼承mysql源中的所有配置,如果子配置中有相同配置,則覆蓋父配置{        sql_query       =       SELECT id,fromid,toid,content FROM say WHERE id > (SELECT max_offset FROM sph_say_counter WHERE id = 1) #從屬記錄大於max_offset後的資料開始索引        sql_query_post  =       REPLACE INTO sph_say_counter(id,max_offset) SELECT 1,MAX(id) FROM say #索引後更新最大記錄,sql_query_pre是執行查詢前執行的語句,sql_query_post是執行查詢後再執行的語句}index delta : mysql{        source          =       delta        path            =       /usr/local/coreseek/var/data/delta}

  此時執行增量索引 /usr/local/coreseek/bin/indexer -c /usr/local/coreseek/etc/csft_mysql.conf delta --rotate  後,便可以通過search搜尋到多出內容的搜尋結果

  可以通過合并索引 /usr/local/coreseek/bin/indexer -c /usr/local/coreseek/etc/csft_mysql.conf --merge mysql delta --rotate --merge-dst-range deleted 0 0  來合并mysql源和delta源的索引 (--merge-dst-range deleted 0 0 是為了防止多個關鍵字指向同一個文檔)

  

  為了在執行索引時也可以更新sph_say_counter表,在source mysql內也加入這句:

sql_query_pre           = REPLACE INTO sph_say_counter(id,max_offset) SELECT 1,MAX(id) FROM say

  此時執行 /usr/local/coreseek/bin/indexer -c /usr/local/coreseek/etc/csft_mysql.conf --all --rotate 便可以重建立立所有索引並更新sph_say_counter表

  

  到此csft_mysql.conf完整配置為:

 View Code

 

  3.將執行索引加入到Linux計劃任務中,定時執行更新,合并,整體索引 

  為了方便,我們將執行整體索引,增量索引,合并索引分別寫到3個shell檔案中

cd /usr/local/coreseek/shvi all.sh/usr/local/coreseek/bin/indexer -c /usr/local/coreseek/etc/csft_mysql.conf --all --rotatevi delta.sh/usr/local/coreseek/bin/indexer -c /usr/local/coreseek/etc/csft_mysql.conf delta --rotate vi merge.sh/usr/local/coreseek/bin/indexer -c /usr/local/coreseek/etc/csft_mysql.conf --merge mysql delta --rotate --merge-dst-range deleted 0 0 

  然後,執行crontab -e 寫入如下內容

*/1 * * * * /bin/sh /usr/local/coreseek/sh/delta.sh >/dev/null 2>&1 ##每1分鐘執行增量索引*/5 * * * * /bin/sh /usr/local/coreseek/sh/merge.sh >/dev/null 2>&1 ##每5分鐘合并索引30 1 * * *  /bin/sh /usr/local/coreseek/sh/all.sh >/dev/null 2>&1   ##每天的1:30執行整體索引
具體執行時間隨自己定義,關於linux計劃任務的更多配置,你可以點擊此傳送查看詳細。關於rotate,可以點此查看詳細。此步驟後,mysql資料來源配置基本完畢,詳細mysql資料來源配置,可以到點此查看,關於設定檔詳細解析,可以點此查看。

 

四,PHP使用Sphinx/Coreseek的三種方式:

 

四-1,使用sphinxapi.php

   在/coreseek安裝包/testpack/api目錄下提供了PHP的介面檔案 sphinxapi.php,這個檔案包含一個SphinxClient的類,你可以複製到項目目錄下包含使用。

 1 <?php 2  3 /* 4    test_sph.php  5     SphinxClient類測試 6 */ 7  8 $key=trim($_GET[‘key‘]); 9 echo $key;10 include(‘sphinxapi.php‘);11 12 $sp=new SphinxClient();13 $sp->SetServer(‘localhost‘,9312);14 $sp->SetArrayResult(true);15 $sp->SetMatchMode(SPH_MATCH_ALL);16 $sp->SetSortMode(SPH_SORT_RELEVANCE);17 $res=$sp->Query($key,‘mysql‘);18 19 echo ‘<pre>‘;20 print_r($res);21 echo ‘</pre>‘;22 23 if(isset($res[‘matches‘])&&count($res[‘matches‘])>0)24 {25     $mysql=new PDO("mysql:localhost;dbname=test_qq",‘root‘,‘123‘);26     $mysql->query(‘set names utf8‘);27     $mysql->query(‘use test_qq‘);28     $sql=‘select * from say where id in(‘;29 30     foreach ($res[‘matches‘] as $v)31     {32         $sql.=$v[‘id‘].‘,‘;33     }34     $sql=trim($sql,‘,‘).‘)‘;35 36     echo $sql;37     foreach($mysql->query($sql) as $v)38     {39         echo ‘<pre>‘;40         print_r($v);41         echo ‘</pre>‘;42     }43 }44 else45 {46     echo ‘沒有記錄‘;47 }

 

   瀏覽器輸入localhost/test_sph.php?key=搜尋索引鍵   查看搜尋結果

 

四-2,安裝php的sphinx擴充

   除了可以直接包含 sphinxapi.php檔案,還可以通過安裝php的sphinx擴充模組來直接調用SphinxClient,且效率比包含api檔案要高,安裝sphinx需要依賴libsphinxclient包,因此先安裝。

  1,安裝libsphinxevent
 1 # cd /coreseek安裝包目錄/csft-4.1/api/libsphinxclient/ 2 # ./configure  --prefix=/usr/local/sphinxclient 3  4 configure: creating ./config.status 5 config.status: creating Makefile 6 config.status: error: cannot find input file: Makefile.in   #報錯configure失敗     7  8 //處理configure報錯 9 編譯過程中報了一個config.status: error: cannot find input file: src/Makefile.in這個的錯誤,然後運行下列指令再次編譯就能通過了:10 # aclocal11 # libtoolize --force12 # automake --add-missing13 # autoconf14 # autoheader15 # make clean16 17 //從新configure編譯18 # ./configure19 20 # make && make install
  2,安裝sphinx的PHP擴充
 1 http://pecl.php.net/package/sphinx 2 # wget http://pecl.php.net/get/sphinx-1.3.0.tgz 3 # tar zxvf sphinx-1.3.0.tgz 4 # cd sphinx-1.3.0 5 # phpize 6 # ./configure --with-php-config=/usr/bin/php-config --with-sphinx=/usr/local/sphinxclient 7 # make && make install 8 # cd /etc/php.d/ 9 # cp gd.ini  sphinx.ini10 # vi sphinx.ini11 12 extension=sphinx.so13 14 # service php-fpm restart

 

  安裝完畢後,你可以使用四-2的 test_sqh.php測試搜尋

  

  分頁測試:
 1 <?php 2     header("Content-type: text/html; charset=utf-8"); 3     require("./sphinxapi.php"); 4     $s = new SphinxClient; 5     $s->setServer("192.168.252.132", 9312); 6      7     //SPH_MATCH_ALL, 匹配所有查詢詞(預設模式); SPH_MATCH_ANY, 匹配查詢詞中的任意一個; SPH_MATCH_EXTENDED2, 支援特殊運算子查詢 8     $s->setMatchMode(SPH_MATCH_ALL); 9     $s->setMaxQueryTime(30);                                        //設定最大搜尋時間10     $s->SetArrayResult(false);                                        //是否將Matches的key用ID代替11     $s->SetSelect ( "*" );                                            //設定返回資訊的內容,等同於SQL12     $s->SetRankingMode(SPH_RANK_BM25);                                //設定評分模式,SPH_RANK_BM25可能使包含多個詞的查詢的結果品質下降。 13     //$s->SetSortMode(SPH_SORT_EXTENDED);                            //發現增加此參數會使結果不準確14     //$s->SetSortMode(SPH_SORT_EXTENDED,"from_id asc,id desc");        //設定匹配項的排序模式, SPH_SORT_EXTENDED按一種類似SQL的方式將列組合起來,升序或降序排列。15     $weights = array (‘company_name‘ => 20);16     $s->SetFieldWeights($weights);                                    //設定欄位權重17     $s->SetLimits ( 0, 30, 1000, 0 );                                //設定結果集位移量  SetLimits (便宜量,匹配項數目,查詢的結果集數預設1000,閥值達到後停止)18     //$s->SetFilter ( $attribute, $values, $exclude=false );        //設定屬性過濾19     //$s->SetGroupBy ( $attribute, $func, $groupsort="@group desc" );    //設定分組的屬性20     $res = $s->query(‘@* "汽車"‘,‘main‘,‘--single-0-query--‘); #[寶馬]關鍵字,[news]資料來源source21     22     23     //代碼高亮24     $tags = array();25     $tags_name = array();26     foreach($res[‘matches‘] as $key=>$value){27         $tags[] = $value[‘attrs‘];28           $company_name[] = $value[‘attrs‘][‘company_name‘];29           $description[] = $value[‘attrs‘][‘description‘];30     }31     $company_name = $s->BuildExcerpts ($company_name, ‘main‘, ‘汽車‘, $opts=array() );        //執行高亮,這裡索引名字千萬不能用*32     $description = $s->BuildExcerpts ($description, ‘main‘, ‘汽車‘, $opts=array() );        //執行高亮,這裡索引名字千萬不能用*33     foreach($tags as $k=>$v)34     {35         $tags[$k][‘company_name‘] = $company_name[$k];    //高亮後覆蓋36         $tags[$k][‘description‘] = $description[$k];    //高亮後覆蓋37     }38     39     // 高亮後覆蓋40     $i = 0;41     foreach($res[‘matches‘] as $key=>$value){42         $res[‘matches‘][$key] = $tags[$i];43         $i++;44     }45     46     $err = $s->GetLastError();47     48     echo ‘<pre>‘;49     var_export($res);50     var_export($err);51     echo ‘</pre>‘;

 

   

  更多SphinxClient類的資料,可以參考官方文檔。

 

四-3,為 MySQL 5.5.x 編譯安裝 SphinxSE

 

  直接安裝SphinxSe作為mysql的儲存引擎,php的無需作任何改變,即可使用sphinx的全文索引。

#---------------MySQL 5.5 基本設定編譯-----------#以下指令中的VERSION表示MySQL的版本,例如:5.5.8,或者5.5.9$ tar xzvf coreseek-4.1-beta.tar.gz$ tar xzvf mysql-VERSION.tar.gz #就是上面下載的mysql源碼包$ cp -R coreseek-4.1-beta/csft-4.1/mysqlse mysql-VERSION/storage/sphinx#上面語句是將mysqlse檔案夾複製到storage檔案夾下並更名為sphinx,請注意$ cd mysql-VERSION$ cmake . -DCMAKE_BUILD_TYPE=Release -DWITH_SPHINX_STORAGE_ENGINE=1 #如果提示沒有命令 先"yum -y install cmake" 安裝cmake#如果上面語句報“Warning: Bison executable not found in PATH”,則安裝bison,再運行此語句#如果提示缺少ncurses庫,則 apt-get install libncurses-dev 或 yum -y install ncurses-devel 安裝ncurses庫後,刪除CMakeCache.txt檔案,再重新cmake即可#如要查看cmake可用參數,請執行:cmake . -LH$ make#----------將SphinxSE安裝到已經安裝的MySQL 5.5中-----------#首先執行:MySQL 5.5 基本設定編譯過程#特別注意:需要選擇與當前已安裝的MySQL 5.5對應的版本進行編譯$ cp storage/sphinx/ha_sphinx.so /path_to_your_mysql_5.5/lib/plugin$ mysql -uroot -p???mysql>install plugin sphinx soname "ha_sphinx.so";mysql>show engines;#ENGINE列表顯示出SPHINX表示安裝成功

 

測試使用SphinxSe:

#-------------------------測試SphinxSe--------------------------------------mysql> use test_qq;mysql> CREATE TABLE documents_sphinxse-> (-> id INTEGER UNSIGNED NOT NULL,-> weight INTEGER NOT NULL,-> query VARCHAR(3072) NOT NULL,-> group_id INTEGER,-> INDEX(query)-> ) ENGINE=SPHINX CONNECTION="sphinx://localhost:9312/mysql";#-----------執行sphinxse查詢-----------------------------mysql>SELECT * FROM documents_sphinxse WHERE query=‘網路搜尋;mode=any‘;#--------執行關聯SphinxSE查詢,擷取未經處理資料資訊:-----------
mysql>SELECT dse.*, d.title FROM documents_sphinxse AS dse LEFT JOIN documents AS d USING(id) WHERE query=‘網路搜尋;mode=any‘;

 

 

五,參考文檔

    http://blog.csdn.NET/e421083458/article/details/21529969

  http://www.coreseek.cn/products-install/sphinxse/

  http://blog.csdn.Net/keyunq/article/details/45129867

  http://www.cnblogs.com/yjf512/p/3598332.html

 

 

文章來源:http://www.cnblogs.com/GaZeon/p/5327578.html

【整理】Linux下中文檢索引擎coreseek4安裝,以及PHP使用sphinx的三種方式(sphinxapi,sphinx的php擴充,SphinxSe作為mysql儲存引擎)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.