laravel 如何使用方便的使用es实现全文搜索功能?
本扩展包支持IK分词设置。
在按下文操作前请先阅读 laravel scout 全文搜索文档
安装
您可以通过composer安装软件包 wannanbigpig/laravel-scout-elastic:
composer require wannanbigpig/laravel-scout-elastic
Laravel 会自动注册驱动服务提供者。
Elasticsearch 配置
安装完成后,您应该使用vendor:publish Artisan命令发布Scout配置文件。该命令将把scout.php配置文件发布到应用程序的config目录中:
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
发布Laravel Scout包配置后,您需要将驱动程序设置为弹性搜索并添加其配置:
// config/scout.php
<?php
return [
// ...
'driver' => env('SCOUT_DRIVER', 'elasticsearch'),
// ...
/*
|--------------------------------------------------------------------------
| Elasticsearch Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your Elasticsearch settings.
|
*/
'elasticsearch' => [
'hosts' => [env('ELASTICSEARCH_HOST', 'http://127.0.0.1:9200')],
// 如果你的es没有开启校验账号密码则忽略该配置
// 'auth' => [
// 'username' => 'elastic',
// 'password' => 'password copied during Elasticsearch start',
// ],
// index_ 后跟索引名称。如果不需要自定义索引分词模式,则跳过下面的设置
'index_article' => [
'settings' => [
'number_of_shards' => 5,
'number_of_replicas' => 1,
],
'mappings' => [
"properties" => [
"title" => [
"type" => "text",
"analyzer" => "ik_max_word",
"search_analyzer" => "ik_smart",
"fields" => ["keyword" => ["type" => "keyword", "ignore_above" => 256]],
],
],
],
],
],
];
使用
命令
// 创建索引
php artisan scout:index article
// 删除
php artisan scout:delete-index article
// 批量更新数据到es
// Article这个model需引入use Laravel\Scout\Searchable;
// 想自定义同步到es的字段需自己实现toSearchableArray这个方法
php artisan scout:import "App\Models\Article"
搜索示例
use App\Models\Article;
// $condition = "test";
// ... or
// $condition = [
// "title" => "test",
// "abstract" => "test"
// ];
// ... or
$keyword = "test";
$source = [1,2];
$startTime = '2023-05-01T00:00:00.000+0800';
$endTime = '2023-05-20T00:00:00.000+0800';
$condition = [
// 该字段仅用来区分是否选择自定义es搜索body请求体,不会实际发送至es
"_customize_body" => 1,
"query"=>[
"bool" => [
"should" => [
[
"match" => [
"title" => ["query" => $keyword, 'boost' => 5]
]
],
[
"match" => [
"abstract" => ["query" => $keyword, 'boost' => 3]
]
],
],
"must" => [
[
"terms" => ["source" => $source]
],
[
"range" => [
"created_at" => [
'gte' => $startTime,
'lte' => $endTime
]
]
]
]
],
],
];
$data = Article::search($condition)
->orderBy('_score', 'desc')
->paginate(10);
更多使用方法 Laravel Scout official documentation.
参考:
https://github.com/ErickTamayo/laravel-scout-elastic
https://github.com/laravel/scout/tree/10.x
https://github.com/medcl/elasticsearch-analysis-ik文章来源:https://www.toymoban.com/news/detail-464477.html
License
The MIT License (MIT).文章来源地址https://www.toymoban.com/news/detail-464477.html
到了这里,关于laravel如何使用scout+elasticsearch搜索,并支持IK分词的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!