下面由laravel教程栏目给大家介绍如何轻松集成新版elasticsearch7.9中文搜索到laravel7项目,希望对需要的朋友有所帮助!
只需五步骤:
1、启动 集成ik中文分词插件的elasticsearch7.9 docker镜像
课程推荐→:《elasticsearch全文搜索实战》(实战视频)
来自课程《千万级数据并发解决方案(理论+实战)》
2、laravel7 配置 scout
3、配置 model模型
4、导入数据
5、搜索
演示地址
www.ar414.com/search?query=php%e5%...搜索范围
文章内容标题标签结果权重
出现关键词数量出现关键词次数搜索页面
高亮显示分词显示结果分页前言主要是博客刚好想做个搜索,顺便就整理成文章
laravel + elasticsearch 很多前辈都写过教程和案例,但是随着elasticsearch和laravel的版本升级 以前的文章很多都不适用新版本的,建议大家使用任何开源项目时应该过一遍文档以当前使用的版本文档为主,教程为辅
elasticsearch 7.9laravel 7elasticsearch-analysis-ik v7.9参考ik 中文分词插件elasticsearch 官方文档使用集成ik中文分词插件的elasticsearch拉取docker$ docker pull ar414/elasticsearch-7.9-ik-plugin
创建日志和数据存储目录本地映射到docker容器内,防止docker重启数据丢失
$ mkdir -p /data/elasticsearch/data$ mkdir -p /data/elasticsearch/log$ chmod -r 777 /data/elasticsearch/data$ chmod -r 777 /data/elasticsearch/log
运行docker run -d -p 9200:9200 -p 9300:9300 -e discovery.type=single-node -v /data/elasticsearch/data:/var/lib/elasticsearch -v /data/elasticsearch/log:/var/log/elasticsearch ar414/elasticsearch-7.9-ik-plugin
验证$ curl http://localhost:9200{ name : 01ac21393985, cluster_name : docker-cluster, cluster_uuid : h8l336qcrb2i1aydov04og, version : { number : 7.9.0, build_flavor : default, build_type : docker, build_hash : a479a2a7fce0389512d6a9361301708b92dff667, build_date : 2020-08-11t21:36:48.204330z, build_snapshot : false, lucene_version : 8.6.0, minimum_wire_compatibility_version : 6.8.0, minimum_index_compatibility_version : 6.0.0-beta1 }, tagline : you know, for search}
测试中文分词curl -x post http://localhost:9200/_analyze?pretty -h 'content-type: application/json' -d'{ analyzer: ik_max_word, text: laravel天下无敌}'{ tokens : [ { token : laravel, start_offset : 0, end_offset : 7, type : english, position : 0 }, { token : 天下无敌, start_offset : 7, end_offset : 11, type : cn_word, position : 1 }, { token : 天下, start_offset : 7, end_offset : 9, type : cn_word, position : 2 }, { token : 无敌, start_offset : 9, end_offset : 11, type : cn_word, position : 3 } ]}
laravel 项目中使用 elasticsearch
elasticsearch官方有提供 sdk,在 laravel 项目中可以更加优雅快速的接入 elasticsearch,laravel 本身有提供 scout全文搜索 的解决方案,我们只需将默认的 algolia 驱动 替换成elasticsearch驱动。
安装laravel/scoutmatchish/laravel-scout-elasticsearch$ composer require laravel/scout$ composer require matchish/laravel-scout-elasticsearch
配置生成 scout 配置文件(config/scout.php)
$ php artisan vendor:publish --provider=laravel\scout\scoutserviceprovidercopied file [\vendor\laravel\scout\config\scout.php] to [\config\scout.php]publishing complete.
指定 scout 驱动
第一种:在.env文件中指定(建议)scout_driver=matchish\scoutelasticsearch\engines\elasticsearchengine
第二种:在config/scout.php直接修改默认驱动'driver' => env('scout_driver', 'algolia')改为'driver' => env('scout_driver', 'matchish\scoutelasticsearch\engines\elasticsearchengine')
指定elasticsearch服务ip端口
如果使用docker部署则使用docker0的ip,linux通过ifconfig查看
在.env中配置
elasticsearch_host=172.17.0.1:9200
注册服务
config/app.php
'providers' => [ // other service providers \matchish\scoutelasticsearch\elasticsearchserviceprovider::class],
清除配置缓存
$ php artisan config:clear
至此 laravel 已经接入 elasticsearch
实际业务中使用需求
通过博客右上角的搜索框可以搜索到与关键词相关的文章,从以下几点匹配
文章内容文章标题文章标签涉及到2张 mysql表 以及字段
articletitletagsarticle_contentcontent为文章配置 elasticsearch 索引创建索引配置文件(config/elasticsearch.php)
$ touch config/elasticsearch.php
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 使用文档
引入laravel scout
namespace app\models\blog; use laravel\scout\searchable; class article extends blogbasemodel { use searchable; }
指定索引(刚刚配置文件中的elasticsearch.indices.mappings.blog-articles)
/** * 指定索引 * @return string */ public function searchableas() { return 'blog-articles'; }
设置导入索引的数据字段
/** * 设置导入索引的数据字段 * @return array */ public function tosearchablearray() { return [ 'content' => articlecontent::query() ->where('article_id',$this->id) ->value('content'), 'tags' => implode(',',$this->tags), 'title' => $this->title ]; }
指定 搜索索引中存储的唯一id
/** * 指定 搜索索引中存储的唯一id * @return mixed */ public function getscoutkey() { return $this->id; } /** * 指定 搜索索引中存储的唯一id的键名 * @return string */ public function getscoutkeyname() { return 'id'; }
数据导入其实是将数据表中的数据通过elasticsearch导入到lucene
elasticsearch 是 lucene 的封装,提供了 rest api 的操作接口
一键自动导入: php artisan scout:import导入指定模型: php artisan scout:import ${model}$ php artisan scout:import app\models\blog\articleimporting [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 周杰伦
复杂查询
例如:自定义高亮显示//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();
复杂自定义查询回调中的$client和$body,可根据这两个包进行灵活操作
$client 官方 elasticsearch/elasticsearch package(https://packagist.org/packages/elasticsearch/elasticsearch)
$body ongr/elasticsearch-dsl package(https://packagist.org/packages/ongr/elasticsearch-dsl)
以上就是轻松集成新版elasticsearch7.9中文搜索到laravel7项目的详细内容。