发布于 4年前

在 laravel 中使用 tntsearch,并配置中文搜索

tntsearch 是一个用 PHP 编写的轻量级全文搜索引擎,非常容易在 PHP 项目中使用,这篇文章将介绍如何在 Laravel 项目中安装 tntsearch,以及如何使用jieba 分词让 tntsearch 支持中文搜索。注:我当前使用的 Laravel 版本是 5.8。

准备

配置

  1. 创建 laravel 项目,并安装 Scout Scount 安装过程可以参考官方文档:https://laravel.com/docs/5.8/scout#installation

  2. 安装tntsearch搜索引擎以及驱动器 安装过程可以参考:https://github.com/teamtnt/laravel-scout-tntsearch-driver#installation

  3. 安装jieba-php 安装过程可以参考:https://github.com/fukuball/jieba-php#usage

  4. 打开 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,
    ],
  5. 创建 TokenizerHandler

    // app > handlers > TokenizerHandler.php
    <?php 
    namespace App\Handlers;
    use Fukuball\Jieba\Jieba;
    use Fukuball\Jieba\Finalseg;
    use Fukuball\Jieba\JiebaAnalyse;
    use TeamTNT\TNTSearch\Support\TokenizerInterface;
    class TokenizerHandler implements TokenizerInterface
    {
        public function __construct()
        {
                ini_set('memory_limit', '1024M');
                $options = [
                        'dict' => '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;
        }
    }
©2020 edoou.com   京ICP备16001874号-3