Laravel 下 TNTSearch+jieba-PHP 实现中文全文搜索
##
TNTSearch+jieba-php 实现中文全文搜索;
##
1. laravel new tntsearch (创建项目)
2. php artisan make:model Models/Article -m (建表,模型)
3. 修改 .env 数据库配置项;
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
4. php artisan make:model Models/Article -m (建表,模型)
5: 再确认 php 开启了以下扩展
pdo_sqlite
sqlite3
mbstring
6. composer 加载 laravel-scout-tntsearch扩展包
composer require vanry/laravel-scout-tntsearch
7.添加 Provider config/app.php;
'providers' => [
// ...
/**
* TNTSearch 全文搜索
*/
Laravel\Scout\ScoutServiceProvider::class,
Vanry\Scout\TNTSearchScoutServiceProvider::class,
],
6. composer 加载 中文分词 require jieba-php
composer require fukuball/jieba-php
7.发布配置项
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
8.配置项中增加 tntsearch config/scout.php ;
'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' => [
'的',
'了',
'而是',
],
],
9.增加配置项 .env :
SCOUT_DRIVER=tntsearch
TNTSEARCH_TOKENIZER=jieba
10.型中定义全文搜索;
/app/StoreCourse.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class StoreCourse extends Model
{
use Searchable;
protected $table = "stores_courses";
public $timestamps = false;
protected $primaryKey = 'id';
protected $guarded = [];
protected $fields = [];
/**
* 索引的字段
*
* @return array
*/ public function toSearchableArray()
{ return $this->only('id', 'name', 'image_url');
// return $this->toArray();
}
}
11. php 默认的 memory_limit 是 128M;
为了防止 PHP Fatal error: Allowed memory size of n bytes exhausted ;增加到 256M 以解决内存不够报错的问题;
public function boot()
{
/**
* 增加内存防止中文分词报错
*/
ini_set('memory_limit', "256M");
}
12. 生成索引
php artisan scout:import "App\StoreCourse"
13. 使用
StoreCourse::search('功能齐全的搜索引擎')->get()->toArray()
本作品采用《CC 协议》,转载必须注明作者和本文链接