coreseek實戰(三):全文搜尋在php中應用(使用api介面)

樑子很威武發表於2016-11-22

coreseek實戰(三):全文搜尋在php中應用(使用api介面)

這一篇文章開始學習在php頁面中通過api介面,使用coreseek全文搜尋。

第一步:綜合一下前兩篇文章,coreseek實戰(1)中的資料來源換成實戰(2)中的 mysql 資料來源配置。然後建立索引檔案:

複製程式碼
D:\www\coreseek>bin\indexer -c etc\csft_mysql.conf dede
Coreseek Fulltext 3.2 [ Sphinx 0.9.9-release (r2117)]
Copyright (c) 2007-2011,
Beijing Choice Software Technologies Inc (http://www.coreseek.com)

 using config file 'etc\csft_mysql.conf'...
indexing index 'dede'...
collected 354 docs, 2.2 MB
sorted 0.5 Mhits, 100.0% done
total 354 docs, 2207983 bytes
total 2.117 sec, 1042951 bytes/sec, 167.21 docs/sec
total 2 reads, 0.002 sec, 748.5 kb/call avg, 1.2 msec/call avg
total 9 writes, 0.008 sec, 396.2 kb/call avg, 0.9 msec/call avg
複製程式碼

第二步:安裝並開啟 searchd 服務

在coreseek實戰(一)中,有一部分錯誤的,但已經原文修正,具體見實戰(一)第一步的第5點。

第二步:coreseek php api介面的使用

在coreseek/api目錄下,有個名為 sphinxapi.php 的檔案,這就是php api介面。我們複製一份到網站根目錄下(我這裡是http://localhost/php/),同時在該目錄下建立index.php文件,呆會我們通過該頁面來實現查詢功能。

index.php 頁面程式碼:

複製程式碼
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>coreseek中文全文搜尋在php程式中的應用</title>
</head>
<body>
<h3><font color="blue">coreseek全文搜尋在php程式中應用</font></h3>
<form action="index.php" method="post">
輸入搜尋的關鍵詞:<input type="text" name="keyword" size="30" />
<input type="submit" name="sub" value="搜尋" />
</form>
<hr />
<?php
echo "<pre />";
#引入介面檔案,其實你懂的,就是一個類
require_once('sphinxapi.php');
if(isset($_POST['sub']) && $_POST['keyword'] != ''){
    $keyword = trim($_POST['keyword']);    //接收關鍵詞

    $sph = new SphinxClient();            //例項化 sphinx 物件
    $sph->SetServer('localhost',9312);    //連線9312埠
    $sph->SetMatchMode(SPH_MATCH_ANY);    //設定匹配方式
    $sph->SetSortMode(SPH_SORT_RELEVANCE);    //查詢結果根據相似度排序
    $sph->SetArrayResult(true);                //設定結果返回格式,true以陣列,false以PHP hash格式返回,預設為false
    
    $result = $sph->query($keyword, 'dede');//執行搜尋操作,引數(關鍵詞,索引名)
    print_r($result);
}
?>
複製程式碼

結果返回一個陣列,注意觀察一下,陣列中有一個鍵名為[matches]單元,這就是匹配的結果,我們需要獲取[matches]下的鍵名,即是文件的id。然後再根據 id 來查詢資料庫,獲取到匹配結果裡對應的文章即可,詳細程式碼見下一篇文章。

相關文章