tntsearch 是一个用 PHP 编写的轻量级全文搜索引擎,非常容易在 PHP 项目中使用,这篇文章将介绍如何在 Laravel 项目中安装 tntsearch,以及如何使用jieba 分词让 tntsearch 支持中文搜索。注:我当前使用的 Laravel 版本是 5.8。
准备
teamtnt/laravel-scout-tntsearch-driverLaravel Scout tntsearch 驱动器
配置
创建 laravel 项目,并安装 ScoutScount 安装过程可以参考官方文档:https://laravel.com/docs/5.8/scout#installation
安装tntsearch搜索引擎以及驱动器安装过程可以参考:https://github.com/teamtnt/laravel-scout-tntsearch-driver#installation
安装jieba-php安装过程可以参考:https://github.com/fukuball/jieba-php#usage
打开 config > scout.php 文件,添加 tntsearch 配置数据
'tntsearch' => [ 'storage' => storage_path(), //place where the index files will be stored 'fuzziness' => env('TNTSEARCH_FUZZINESS', true), 'fuzzy' => [ 'prefix_length' => 2, 'max_expansions' => 100, 'distance' => 2 ], 'asYouType' => false, 'searchBoolean' => env('TNTSEARCH_BOOLEAN', false), 'tokenizer' => App\Handlers\TokenizerHandler::class, ],
- 创建 TokenizerHandler
// app > handlers > TokenizerHandler.php 'small' ]; Jieba::init($options); Finalseg::init(); JiebaAnalyse::init(); } public function tokenize($text, $stopwords = []) { return is_numeric($text) ? [] : $this->getTokens($text, $stopwords); } public function getTokens($text, $stopwords = []) { $split = Jieba::cutForSearch($text); return $split; } }