安裝導入WindSearch
環境要求:
- UTF-8編碼
- PHP ≥7.3
- mbstring Extension
- PDO Extension
- SQLite Extension
開始安裝:
在github上將WindSearch下載到本地你喜歡的文件夾,這是一個純PHP的全文檢索引擎
地址:https://github.com/rock365/windsearch(點個star吧親親O(∩_∩)O~~)
再引入入口文件,注意具體文件路徑
require_once 'yourdirname/vendor/autoload.php';
至此,安裝已經全部完成,再無其它任何配置,快不快?
建索引庫
複製修改粘貼即可,跟mysql建表差不多
$mapping = [
//設置索引庫的名稱,比如對應的表名
'name' => 'test',
// 字段配置
'field' => [
[
'name' => 'id',// 主鍵名稱 主鍵必須設置
'type' => 'primarykey', //數據類型為主鍵 必須設置
'primarykey_type' => 'Int_Incremental', // int遞增
],
[
'name' => 'title',
'index' => true,
'type' => 'text',
'analyzer' => 'segment',
],
[
'name' => 'tags',
'index' => true,
'type' => 'keyword',
]
[
'name' => 'score',
'type' => 'numeric',
],
[
'name' => 'time',
'type' => 'date'
],
[
'name' => 'descr',
'type' => 'text',
],
]
];
// 實例化對象
$Wind = new \WindSearch\Index\Wind('test'); //$indexName 當前索引庫的名稱
//檢查是否存在此索引庫
$is_index = $Wind->checkIndex();
// 如果存在此索引庫
if ($is_index) {
//刪除索引庫
$Wind->delIndex();
}
//創建索引庫
$Wind->createIndex($mapping);
導入數據
//實例化引擎
$Wind = new \WindSearch\Index\Wind('test');
// 初始化
$Wind->buildIndexInit();
// 開啓分詞,導入數據時,加true可加快速度
$Wind->loadAnalyzer(true);
// 數據量小(內容少於一萬條),則可以一次性全部導入
// selectAll...
// $result:一次性查詢的所有內容
foreach ($result as $v) {
$Wind->indexer($v);
}
// 批量寫入文件保存
$Wind->batchWrite();
構建索引
// 數據導入結束後,接着可立即調用此方法構建索引
// 注意,數據量大時,此步驟會比較耗時
$Wind->buildIndex();
開始搜索
//實例化引擎
$Wind = new \WindSearch\Index\Wind('test');
//開啓分詞功能
$Wind->loadAnalyzer();
//開始搜索
// 搜索單個字段
$query = [
'match' => [
'field' => [
'name' => 'title',
'query' => $text,
],
'list_rows' => $listRows, //每頁多少條數據
'page' => $page, //第幾頁
]
];
// 搜索接口
$res = $Wind->search($query, $page, $listRows);
// 返回的最終結果,可直接渲染到前台頁面
$resArr = $res['result']['_source'];
結語
以上流程可以快速實現一個PHP全文檢索,當然,這些只是餐前甜點,WindSearch還有更深入、更豐富的搜索功能等你挖掘:
github地址:https://github.com/rock365/windsearch
在線開發文檔:https://rock365.github.io/ 偶爾訪問不穩定,多刷新幾次即可
在github點個star吧親親O(∩_∩)O~~謝謝大家!