vanry/laravel-scout-tntsearch
最新稳定版本:2.4.0
Composer 安装命令:
composer require vanry/laravel-scout-tntsearch
包简介
包含中文分词的 Laravel Scout TNTSearch 驱动,支持 scws, phpanalysis 和 jieba 分词。
README 文档
README
说明:
2.x版本只支持Laravel 5.5以上版本,Laravel 5.5以下版本请使用 1.x版本。
安装
需安装并开启
sqlite扩展
composer require vanry/laravel-scout-tntsearch
Laravel
- 发布
scout配置文件,已安装scout可省略。
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
- 如需修改
tntsearch默认配置,发布tntsearch配置文件。
php artisan vendor:publish --provider="Vanry\Scout\TNTSearchScoutServiceProvider"
Lumen
Lumen 需将服务提供者添加到 bootstrap/app.php
// bootstrap/app.php // 取消注释 $app->withFacades(); $app->withEloquent() // 注意先后顺序 $app->register(Vanry\Scout\LumenServiceProvider::class); $app->register(Laravel\Scout\ScoutServiceProvider::class);
在根目录中创建 config 文件夹, 将 laravel scout 配置文件 scout.php 复制到 config 中。
如需修改 tntsearch 默认配置,则将配置文件 tntsearch.php 复制 config 中进行修改。
启用
在 .env 文件中添加
SCOUT_DRIVER=tntsearch
用法
- 模型添加
Searchable Trait
namespace App; use Illuminate\Database\Eloquent\Model; use Laravel\Scout\Searchable; class Post extends Model { use Searchable; /** * Get the indexable data array for the model. * * @return array */ public function toSearchableArray() { return [ 'id' => $this->id, 'title' => $this->title, 'body' => strip_tags($this->body), ]; } }
- 导入模型 创建索引
# scout 命令 php artisan scout:import 'App\Post' # tntsearch 命令, 性能更好 php artisan tntsearch:import 'App\Post'
- 使用索引进行搜索
Post::search('laravel教程')->get();
中文分词
目前支持 scws, jieba 和 phpanalysis 中文分词,默认使用 phpanalysis 分词。
对比
scws是用C语言编写的php扩展,性能最好,分词效果好,但不支持Windows系统。jieba为python版本结巴分词的php实现,分词效果最好,尤其是新词发现,不足之处是性能较差,占用内存大。phpanalysis是php编写的一款轻量分词器,分词效果不错,性能介于scws和jieba两者之间。
安装
使用 scws 或者 jieba,需安装对应的分词驱动。
- scws
composer require vanry/scws
- jieba
composer require fukuball/jieba-php
在 .env 文件中配置
# scws TNTSEARCH_TOKENIZER=scws # jieba TNTSEARCH_TOKENIZER=jieba
问题
使用 jieba 分词可能会出现内存分配不足的错误信息:
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 20480 bytes)
在代码中增加内存限制即可
ini_set('memory_limit', '1024M');
高亮
默认使用 em 作为高亮 html 标签,在 css 中设置高亮样式即可,也可以自定义高亮标签。
- @highlight 指令
@highlight($text, $query, $tag);
- $text: 要高亮的字段
- $query: 搜索词
- $tag: 高亮的 html 标签
// 高亮 title 字段 @highlight($post->title, $query); // 用 strong 作为高亮标签 @highlight($post->title, $query, 'strong');
- highlight 帮助函数
highlight($post->title, $query); highlight($post->title, $query, 'strong');
- Highlighter 对象
use Vanry\Scout\Highlighter; // ... app(Highlighter::class)->highlight($post->title, $query);
highlight帮助函数和Highlighter对象适合在api等非html视图中使用。
统计信息
- 总下载量: 11.68k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 178
- 点击次数: 1
- 依赖项目数: 1
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2017-09-25