启动 集成 ik 中文分词插件的 Elasticsearch7.9 Docker 镜像
Laravel7 配置 Scout
配置 Model 模型
导入数据
搜索
【社群福利】30G-PHP进阶资料,助力大家都能30K
点击进人暗号:知乎
AR414…
搜索范围
文章内容
标题
标签
结果权重
出现关键词数量
出现关键词次数
搜索页面
高亮显示
分词显示
结果分页
Laravel + Elasticsearch 很多前辈都写过教程和案例,但是随着 Elasticsearch 和 laravel 的版本升级 以前的文章很多都不适用新版本的,建议大家使用任何开源项目时应该过一遍文档以当前使用的版本文档为主,教程为辅
Elasticsearch 7.9
Laravel 7
elasticsearch-analysis-ik v7.9
ik 中文分词插件
elasticsearch 官方文档
拉取 docker
$ docker pull ar414/elasticsearch-7.9-ik-pluginElasticsearch 官方有提供 SDK,在 Laravel 项目中可以更加优雅快速的接入 Elasticsearch,Laravel 本身有提供 Scout 全文搜索 的解决方案,我们只需将默认的 Algolia 驱动 替换成 ElasticSearch驱动。
laravel/scout
matchish/laravel-scout-elasticsearch
$ composer require laravel/scout$ composer require matchish/laravel-scout-elasticsearch1.生成 Scout 配置文件 (config/scout.php)
$ php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"Copied File [\vendor\laravel\scout\config\scout.php] To [\config\scout.php]Publishing complete.2.指定 Scout 驱动
第一种:在.env 文件中指定(建议) SCOUT_DRIVER=Matchish\ScoutElasticSearch\Engines\ElasticSearchEngine 第二种:在 config/scout.php 直接修改默认驱动 'driver' => env('SCOUT_DRIVER', 'algolia')改为'driver' => env('SCOUT_DRIVER', 'Matchish\ScoutElasticSearch\Engines\ElasticSearchEngine')3.指定 Elasticsearch 服务 IP 端口
如果使用 docker 部署则使用 docker0 的 IP,Linux 通过 ifconfig 查看在.env 中配置
ELASTICSEARCH_HOST=172.17.0.1:92004.注册服务
config/app.php
'providers' => [ // Other Service Providers \Matchish\ScoutElasticSearch\ElasticSearchServiceProvider::class],5.清除配置缓存
$ php artisan config:clear至此 laravel 已经接入 Elasticsearch
需求
通过博客右上角的搜索框可以搜索到与关键词相关的文章,从以下几点匹配
文章内容
文章标题
文章标签
涉及到 2 张 Mysql 表 以及字段
article
title
tags
article_content
content
1.创建索引配置文件(config/elasticsearch.php)
$ touch config/elasticsearch.php2.elasticsearch.php 配置字段映射
<?phpreturn [ 'indices' => [ 'mappings' => [ 'blog-articles' => [ "properties"=> [ "content"=> [ "type"=> "text", "analyzer"=> "ik_max_word", "search_analyzer"=> "ik_smart" ], "tags"=> [ "type"=> "text", "analyzer"=> "ik_max_word", "search_analyzer"=> "ik_smart" ], "title"=> [ "type"=> "text", "analyzer"=> "ik_max_word", "search_analyzer"=> "ik_smart" ] ] ] ] ],];analyzer:字段文本的分词器
search_analyzer:搜索词的分词器
根据具体业务场景选择 (颗粒小占用资源多,一般场景 analyzer 使用 ik_max_word,search_analyzer 使用 ik_smart):
ik_max_word:ik 中文分词插件提供,对文本进行最大数量分词
laravel天下无敌 -> laravel,天下无敌 , 天下 , 无敌
ik_smart: ik 中文分词插件提供,对文本进行最小数量分词
laravel天下无敌 -> laravel,天下无敌
建议先看一遍 Laravel Scout 使用文档
1.引入 Laravel Scout
namespace App\Models\Blog; use Laravel\Scout\Searchable; class Article extends BlogBaseModel { use Searchable; }2.指定索引 (刚刚配置文件中的 elasticsearch.indices.mappings.blog-articles)
/** * 指定索引 * @return string */ public function searchableAs() { return 'blog-articles'; }3.设置导入索引的数据字段
/** * 设置导入索引的数据字段 * @return array */ public function toSearchableArray() { return [ 'content' => ArticleContent::query() ->where('article_id',$this->id) ->value('content'), 'tags' => implode(',',$this->tags), 'title' => $this->title ]; }4.指定 搜索索引中存储的唯一 ID
/** * 指定 搜索索引中存储的唯一ID * @return mixed */ public function getScoutKey() { return $this->id; } /** * 指定 搜索索引中存储的唯一ID的键名 * @return string */ public function getScoutKeyName() { return 'id'; }一键自动导入: php artisan scout:import
导入指定模型: php artisan scout:import ${model}
$ php artisan scout:import "App\Models\Blog\Article"Importing [App\Models\Blog\Article]Switching to the new index5/5 [⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬] 100%[OK] All [App\Models\Blog\Article] records have been imported.导入失败,常见原因:
Unresolvable dependency resolving [Parameter #0 [ integer $retries ]] in class Elasticsearch\Transport解决:修改配置后,没有清除配置缓存
invalid_index_name_exception解决: searchableAs 配置错误,为索引创建别名后,指定别名
检查索引是否正确
$ curl -XGET http://localhost:9200/blog-articles/_mapping?pretty{ "blog-articles_1598362919" : { "mappings" : { "properties" : { "__class_name" : { "type" : "text", "fields" : { "keyword" : { "type" : "keyword", "ignore_above" : 256 } } }, "content" : { "type" : "text", "analyzer" : "ik_max_word", "search_analyzer" : "ik_smart" }, "tags" : { "type" : "text", "analyzer" : "ik_max_word", "search_analyzer" : "ik_smart" }, "title" : { "type" : "text", "analyzer" : "ik_max_word", "search_analyzer" : "ik_smart" } } } }}测试
创建一个测试命令行
$ php artisan make:command ElasticTest代码
<?phpnamespace App\Console\Commands; use App\Models\Blog\Article;use App\Models\Blog\ArticleContent;use Illuminate\Console\Command;use Illuminate\Support\Carbon; class ElasticTest extends Command{ /** * The name and signature of the console command. * * @var string */ protected $signature = 'elasticsearch {query}'; /** * The console command description. * * @var string */ protected $description = 'elasticsearch test'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // $startTime = Carbon::now()->getPreciseTimestamp(3); $articles = Article::search($this->argument('query'))->get()->toArray(); $userTime = Carbon::now()->getPreciseTimestamp(3) - $startTime; echo "耗时(毫秒):{$userTime} \n"; //content在另外一张表中,方便观察测试 这里输出 if(!empty($articles)) { foreach($articles as &$article) { $article = ArticleContent::query()->where('article_id',$article['id'])->value('content'); } } var_dump($articles); }}测试
$ php artisan elasticsearch 周杰伦4.复杂查询
例如:自定义高亮显示
//ONGR\ElasticsearchDSL\Highlight\Highlight ArticleModel::search($query,function($client,$body) { $higlight = new Highlight(); $higlight->addField('content',['type' => 'plain']); $higlight->addField('title'); $higlight->addField('tags'); $body->addHighlight($higlight); $body->setSource(['title','tags']); return $client->search(['index' => (new ArticleModel())->searchableAs(), 'body' => $body->toArray()]); })->raw();Copy复杂自定义查询回调中的 $client 和 $body,可根据这两个包进行灵活操作
PHP面试题汇总,看完这些面试题助力你面试成功,工资必有20-25K
以上内容希望帮助到大家,很多PHPer在进阶的时候总会遇到一些问题和瓶颈,业务代码写多了没有方向感,不知道该从那里入手去提升,对此我整理了一些资料,包括但不限于:分布式架构、高可扩展、高性能、高并发、服务器性能调优、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql优化、shell脚本、Docker、微服务、Nginx等多个知识点高级进阶干货需要的可以免费分享给大家,需要的可以加入我的官方群点击此处。
转自链接: Elasticsearch7.9 Laravel7 项目 喜欢我的文章就点赞关注吧
