Laravel 下 TNTSearch+jieba-PHP 實現中文全文搜尋

vinhson發表於2019-04-17

TNTSearch+jieba-php這套組合可以在不依賴第三方的情況下實現中文全文搜尋;
特別的適合部落格這種小專案;

pdo_sqlite
sqlite3
mbstring

看到 https://learnku.com 社群新上線的檔案推薦功能,作者介紹說是使用了es(elasticsearch)全文搜尋功能,於是我開始使用 es (之前沒用過),首先想到的是找度娘,結果搜尋了好多相關的文件資料,都說需要安裝java環境才能使用es,我就想作為php開發如何一定要用java呢?繼續搜尋尋找其他資料,果然在github裡面找到了別人造的輪子laravel-scout-tntsearch;

1、直接

composer require vanry/laravel-scout-tntsearch

2、新增 Provider ;

'providers' => [
    ...
    /**
     * TNTSearch 全文搜尋
     */
    Laravel\Scout\ScoutServiceProvider::class,
    Vanry\Scout\TNTSearchScoutServiceProvider::class,
],

3、中文分詞

composer require fukuball/jieba-php

4、釋出配置項

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

5、配置項config/scout.php中增加 tntsearch

'tntsearch' => [
    'storage' => storage_path('indexes'), //必須有可寫許可權
    'fuzziness' => env('TNTSEARCH_FUZZINESS', false),
    'searchBoolean' => env('TNTSEARCH_BOOLEAN', false),
    'asYouType' => false,

    'fuzzy' => [
        'prefix_length' => 2,
        'max_expansions' => 50,
        'distance' => 2,
    ],

    'tokenizer' => [
        'driver' => env('TNTSEARCH_TOKENIZER', 'default'),

        'jieba' => [
            'dict' => 'small',
            //'user_dict' => resource_path('dicts/mydict.txt'), //自定義詞典路徑
        ],

        'analysis' => [
            'result_type' => 2,
            'unit_word' => true,
            'differ_max' => true,
        ],

        'scws' => [
            'charset' => 'utf-8',
            'dict' => '/usr/local/scws/etc/dict.utf8.xdb',
            'rule' => '/usr/local/scws/etc/rules.utf8.ini',
            'multi' => 1,
            'ignore' => true,
            'duality' => false,
        ],
    ],

    'stopwords' => [
        '的',
        '了',
        '而是',
    ],
],

6、.env 增加配置項

SCOUT_DRIVER=tntsearch
TNTSEARCH_TOKENIZER=jieba

控制器中:

public function search(){
    $data = Article::search('tnt')->get()->toArray();
    dd($data);
}

在模型中我們新增需要搜尋的欄位:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Article extends Model
{
    use Searchable;

    /**
     * 索引的欄位
     *
     * @return array
     */
    public function toSearchableArray()
    {
        return $this->only('id', 'title', 'content');

       // return $this->toArray();
    }
}

生成索引:

php artisan scout:import "App\Model\Article"

然後我們就可以使用訪問路由了:http://boke.com/search

laravel下TNTSearch+jieba-php實現中文全文搜尋

大功告成!

注:上面生成索引執行過一次就不需要操作了,當我們新增文章的時候回自動新增索引

執行php artisan scout:import "App\Model\Article" 生成的檔案在配置項中 'storage' => storage_path('indexes') 配置

不要輕易放棄。學習成長的路上,我們長路漫漫,只因學無止境

Don't give up easily. On the way of learning and growing up, we have a long way to go, just because there is no end to learning.

相關文章