只需五步骤:

启动 集成 ik 中文分词插件的 Elasticsearch7.9 Docker 镜像

Laravel7 配置 Scout

配置 Model 模型

导入数据

搜索

PHP进阶30K资料,免费获取:

演示地址

搜索范围

文章内容

标题

标签

结果权重

出现关键词数量

出现关键词次数

搜索页面

高亮显示

分词显示

结果分页

前言

主要是博客刚好想做个搜索,顺便就整理成文章

Laravel + Elasticsearch 很多前辈都写过教程和案例,但是随着 Elasticsearch 和 laravel 的版本升级 以前的文章很多都不适用新版本的,建议大家使用任何开源项目时应该过一遍文档以当前使用的版本文档为主,教程为辅

Elasticsearch 7.9

Laravel 7

elasticsearch-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/scout

matchish/laravel-scout-elasticsearch

$ composer require laravel/scout$ composer require matchish/laravel-scout-elasticsearch

配置

1.生成 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:9200

4.注册服务

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

为文章配置 Elasticsearch 索引

1.创建索引配置文件(config/elasticsearch.php)

$ touch config/elasticsearch.php

2.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'; }

数据导入

其实是将数据表中的数据通过 Elasticsearch 导入到 LuceneElasticsearch 是 Lucene 的封装,提供了 REST API 的操作接口

一键自动导入: 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

代码

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

复杂自定义查询回调中的

body,可根据这两个包进行灵活操作

最全的大厂面试题:

喜欢我的文章就关注我吧,持续更新中.....

以上内容希望帮助到大家,很多PHPer在进阶的时候总会遇到一些问题和瓶颈,业务代码写多了没有方向感,不知道该从那里入手去提升,对此我整理了一些资料,包括但不限于:分布式架构、高可扩展、高性能、高并发、服务器性能调优、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql优化、shell脚本、Docker、微服务、Nginx等多个知识点高级进阶干货需要的可以免费分享给大家,需要的可以加入我的官方群点击此处。

php to es7,只需五步 集成新版 Elasticsearch7.9 中文搜索 到你的 Laravel7 项目相关推荐

  1. 网站优化只需五步技巧分享推广无界限

    目前很多企业或者个人的网站都已经很普遍使用了,但是一个网站有好的排名和流量就必须要有好的优化,并且网站自身的关键词优化布局也是非常重要的,不过网站优化一般只需五步就可以达到效果,这五步你都知道吗? 我 ...

  2. 只需五步学会Maven 3.6.1OR 3.6.3及其他版本的下载安装与配置【图文详解】

    第一步,下载并解压缩包 ​第二步,配置两个环境变量 ​第三步,测试是否安装成功 ​第四步,指定本地仓库的路径 第五步,修改镜像仓库 第一步,下载并解压缩包 Maven官方下载地址:https://ma ...

  3. 点击复制内容到手机粘贴板(简洁易懂-只需五步)

    点击按钮复制内容到手机粘贴板 只需简单五步↓ 第一步 npm install clipboard --save 第二步 在需要的页面引入(注:路径根据文件-/) 代码如下↓ <script> ...

  4. (只需五步)ChatGPT接入微信的攻略

    先来看下用弱智问题对战ChatGPT的效果: 再看看程序代码能力: 你也可以用它来写作业学习: 接下来,就是把ChatGPT接入微信的教程: 一共五步,很简单的: 1.进入openAI api 官网登 ...

  5. 只需五步!哈佛学霸教你用Python分析相亲网站数据,在两万异性中找到真爱

    大数据文摘出品 来源:Wired 编译:啤酒泡泡.张大笔茹.张睿毅.牛婉杨 想脱单?那还不容易! 如果身在美国,就像其余四千万单身男人一样,注册一下Match.com, J-Date和OkCupid等 ...

  6. 无法启动游戏 因为计算机,WeGame只需五步即可解决游戏无法启动的问题!

    对于平时有事儿没事儿都爱玩游戏的小伙伴们来说,想必WeGame大家一定都不陌生.它是一款腾讯发布的游戏平台,有点类似于Steam,在WeGame游戏平台中,拥有种类繁多的游戏,比如目前比较热门的使命召 ...

  7. cad批量打印_还为批量打印CAD图纸而发愁?只需五步,3秒打印百张图纸!

    还有将近两个星期就要过年! 是不是很期待!很兴奋呢? 你以为我要和你说过年?大错特错,今天要和大家聊一聊,过年之前工作上的那些事! 都知道CAD绘图设计,是一个每天知道要进行CAD格式转换不下10遍的 ...

  8. (只需五步)注册谷歌账号详细步骤,解决“此电话号码无法验证”问题

    目录 第一步:打开google浏览器 第二步:设置语言为英语(美国) 第三步:点击重新启动,重启浏览器 第四步:开始注册 第五步,成功登录google账号! 如果出现这样的原因,按教程一步步来,就可以 ...

  9. 只需五步,彻底杜绝被蹭网!

    无线网络明明带宽足够,但是网速却很慢?很可能你被蹭网了! 被蹭网是一件很烦人的事情,一些用户往往由于缺乏相关知识而感到不知所措,甚至为此焦头烂额.这次我们通过对路由器进行一些简单的设置,分享一些简单而 ...

最新文章

  1. shell 使用数组作为函数参数的方法
  2. 编写 Debugging Tools for Windows 扩展,第 1 部分 (windbg 插件 扩展)
  3. Java虚拟机学习(5):内存调优
  4. ubuntu c mysql_Ubuntu下MySql和C连接的一些问题
  5. arm9 adc及触摸屏
  6. Python中__init__和__del__方法介绍
  7. kubernetes相关命令
  8. Android仿微信语音聊天功能
  9. 【双清/双wipe】使用adb命令进行双清/双wipe
  10. 直播绿幕抠图的例子(绿幕抠图直播实例参考)
  11. 计算机二级的Word知识点,计算机二级word知识点
  12. 【CXY】JAVA基础 之 Runtime
  13. linux编译sqrt,linux c sqrt
  14. 【html】关于doctype
  15. html怎么制作一个歌单,如何制作属于自己的个性歌单 | Listen1
  16. 常见蛋白质种类_常见蛋白粉种类大全,你选择对了吗?
  17. 财报季观察:为什么小米业绩增长了,股价反而下跌?
  18. mac virtualbox 安装centeros
  19. 西门子atch指令详解_西门子plc指令大全详解
  20. 新概念二册 Lesson 8 The best and the worst最好的和最差的 (形容词和副词比较级)

热门文章

  1. ctf:kali2:端口扫描:nmap和portscan
  2. dne服务器没检测到有响应,设备或资源dns没检测到有响应 网络无法连接
  3. 批量提取PDF和图片发票信息 2.2
  4. app如何助推用户从pc端转向手机端
  5. java 量化指标_量化投资学习笔记13——各种指标的绘图、计算及交易策略
  6. 动态路由、RIP以及IGRP路由的配置
  7. unity-IL2CPP工程打包失败记录
  8. 人工智能系列电子书分享
  9. 酶促反应动力学_酶促反应动力学讲解.ppt
  10. 记录mysql数据库被攻击