只需五步 集成新版 Elasticsearch7.9 中文搜索 到你的 Laravel7 项目

ar414 5分钟 集成新版 Elasticsearch7.9 中文搜索 到你的 Laravel7 项目

只需五步骤:

  1. 启动 集成ik中文分词插件的Elasticsearch7.9 Docker镜像
  2. Laravel7 配置 Scout
  3. 配置 Model模型
  4. 导入数据
  5. 搜索

演示地址

ar414 5分钟 集成新版 Elasticsearch7.9 中文搜索 到你的 Laravel7 项目

ar414

https://www.ar414.com

搜索范围

  • 文章内容
  • 标题
  • 标签

结果权重

  1. 出现关键词数量
  2. 出现关键词次数

搜索页面

  • 高亮显示
  • 分词显示
  • 结果分页

前言

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

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

参考

使用集成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

matchish/laravel-scout-elasticsearch

Elasticsearch官方有提供 SDK,在 Laravel 项目中可以更加优雅快速的接入 Elasticsearch,Laravel 本身有提供 Scout全文搜索 的解决方案,我们只需将默认的 Algolia 驱动 替换成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.
  1. 指定 Scout 驱动
  • 第一种:在.env文件中指定(建议)
SCOUT_DRIVER=Matchish\ScoutElasticSearch\Engines\ElasticSearchEngine
  • 第二种:在config/scout.php直接修改默认驱动
'driver' => env('SCOUT_DRIVER', 'algolia')
改为
'driver' => env('SCOUT_DRIVER', 'Matchish\ScoutElasticSearch\Engines\ElasticSearchEngine')
  1. 指定Elasticsearch服务IP端口

    如果使用docker部署则使用docker0的IP,Linux通过ifconfig查看

    .env中配置

ELASTICSEARCH_HOST=172.17.0.1:9200
  1. 注册服务
    config/app.php
'providers' => [
    // Other Service Providers
    \Matchish\ScoutElasticSearch\ElasticSearchServiceProvider::class
],
  1. 清除配置缓存
$ php artisan config:clear

至此 laravel 已经接入 Elasticsearch

实际业务中使用

需求

14分钟14秒 集成 Elasticsearch中文搜索 到你的 Laravel 项目

通过博客右上角的搜索框可以搜索到与关键词相关的文章,从以下几点匹配

  • 文章内容
  • 文章标题
  • 文章标签

涉及到2张 Mysql表 以及字段

  • article
    • title
    • tags
  • article_content
    • content

为文章配置 Elasticsearch 索引

  1. 创建索引配置文件(config/elasticsearch.php)
$ touch config/elasticsearch.php
  1. elasticsearch.php 配置字段映射
<?php
return [
    '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导入到Lucene
Elasticsearch 是 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 index
5/5 [⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬⚬] 100%
[OK] All [App\Models\Blog\Article] records have been imported.

导入失败,常见原因:

  • Unresolvable dependency resolving [Parameter #0 [ <required> 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"
        }
      }
    }
  }
}

测试

  1. 创建一个测试命令行
$ php artisan make:command ElasticTest
  1. 代码
<?php

namespace 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);

    }
}

  1. 测试
$ php artisan elasticsearch 周杰伦
ar414 5分钟 集成新版 Elasticsearch7.9 中文搜索 到你的 Laravel7 项目
  1. 高亮显示片段
    高亮显示需要自定义查询,核心代码
//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();

自定义查询可参考以两个包灵活开发

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,835评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,598评论 1 295
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,569评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,159评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,533评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,710评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,923评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,674评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,421评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,622评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,115评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,428评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,114评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,097评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,875评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,753评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,649评论 2 271