目錄
使用整合ik中文分詞外掛程式的Elasticsearch" > 使用整合ik中文分詞外掛程式的Elasticsearch
首頁 php框架 Laravel 輕鬆整合新版Elasticsearch7.9中文搜尋到Laravel7項目

輕鬆整合新版Elasticsearch7.9中文搜尋到Laravel7項目

Sep 16, 2020 am 09:15 AM
php laravel

以下由Laravel教學專欄為大家介紹如何輕鬆整合新版Elasticsearch7.9中文搜尋到Laravel7項目,希望對需要的朋友有幫助!


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

只需五個步驟:

1、啟動整合ik中文分詞外掛程式的Elasticsearch7.9 Docker映像

課程推薦→:《elasticsearch全文搜尋實戰》(實戰影片)

來自課程《千萬級資料並發解決方案(理論實戰)》

2、Laravel7 配置Scout

3、配置Model模型

4、導入資料

5、搜尋

#示範位址

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

www.ar414. com/search?query=php�%...

搜尋範圍

  • 文章內容
  • 標題
  • 標籤

#結果權重

  1. 出現關鍵字數量
  2. 出現關鍵字次數

搜尋頁面

  • #高亮顯示
  • 分詞顯示
  • 結果分頁

#前言

主要是部落格剛好想做個搜尋,順便就整理成文章

Laravel Elasticsearch 很多前輩都寫過教程和案例,但是隨著Elasticsearch和laravel的版本升級以前的文章很多都不適用新版本的,建議大家使用任何開源專案時應該過一遍文件以目前使用的版本文件為主,教程為輔

  • Elasticsearch 7.9
  • Laravel 7
  • elasticsearch-analysis-ik v7.9

參考

  • 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
登入後複製

輕鬆整合新版Elasticsearch7.9中文搜尋到Laravel7項目
驗證<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">$ curl http://localhost:9200{   &quot;name&quot; : &quot;01ac21393985&quot;,  &quot;cluster_name&quot; : &quot;docker-cluster&quot;,  &quot;cluster_uuid&quot; : &quot;h8L336qcRb2i1aydOv04Og&quot;,  &quot;version&quot; : {     &quot;number&quot; : &quot;7.9.0&quot;,    &quot;build_flavor&quot; : &quot;default&quot;,    &quot;build_type&quot; : &quot;docker&quot;,    &quot;build_hash&quot; : &quot;a479a2a7fce0389512d6a9361301708b92dff667&quot;,    &quot;build_date&quot; : &quot;2020-08-11T21:36:48.204330Z&quot;,    &quot;build_snapshot&quot; : false,    &quot;lucene_version&quot; : &quot;8.6.0&quot;,    &quot;minimum_wire_compatibility_version&quot; : &quot;6.8.0&quot;,    &quot;minimum_index_compatibility_version&quot; : &quot;6.0.0-beta1&quot;   },  &quot;tagline&quot; : &quot;You Know, for Search&quot;}</pre><div class="contentsignin">登入後複製</div></div>測試中文分詞<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">curl -X POST &quot;http://localhost:9200/_analyze?pretty&quot; -H 'Content-Type: application/json' -d' {   &quot;analyzer&quot;: &quot;ik_max_word&quot;,   &quot;text&quot;:     &quot;laravel天下无敌&quot; } '{   &quot;tokens&quot; : [     {       &quot;token&quot; : &quot;laravel&quot;,      &quot;start_offset&quot; : 0,      &quot;end_offset&quot; : 7,      &quot;type&quot; : &quot;ENGLISH&quot;,      &quot;position&quot; : 0    },    {       &quot;token&quot; : &quot;天下无敌&quot;,      &quot;start_offset&quot; : 7,      &quot;end_offset&quot; : 11,      &quot;type&quot; : &quot;CN_WORD&quot;,      &quot;position&quot; : 1    },    {       &quot;token&quot; : &quot;天下&quot;,      &quot;start_offset&quot; : 7,      &quot;end_offset&quot; : 9,      &quot;type&quot; : &quot;CN_WORD&quot;,      &quot;position&quot; : 2    },    {       &quot;token&quot; : &quot;无敌&quot;,      &quot;start_offset&quot; : 9,      &quot;end_offset&quot; : 11,      &quot;type&quot; : &quot;CN_WORD&quot;,      &quot;position&quot; : 3    }   ]}</pre><div class="contentsignin">登入後複製</div></div>

Laravel 專案中使用Elasticsearch

  • #Elasticsearch
  • 官方有提供SDK,在Laravel 專案中可以更加
  • 優雅
  • 快速的接入Elasticsearch,Laravel 本身有提供Scout全文搜尋的解決方案,我們只需將預設的Algolia 驅動程式替換成
ElasticSearch驅動程式

    安裝
  1. laravel/scout
  2. #輕鬆整合新版Elasticsearch7.9中文搜尋到Laravel7項目
    $ composer require laravel/scout
    $ composer require 輕鬆整合新版Elasticsearch7.9中文搜尋到Laravel7項目
    登入後複製

    #設定
  • 產生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.
    登入後複製
  • 指定Scout 驅動程式

  1. ##第一種:在.env

    檔案中指定(建議)
    SCOUT_DRIVER=Matchish\ScoutElasticSearch\Engines\ElasticSearchEngine
    登入後複製
  2. 第二種:在

    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####

实际业务中使用

需求

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

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

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

涉及到2张 Mysql表 以及字段

  • article
    • title
    • tags
  • article_content
    • content

为文章配置 Elasticsearch 索引

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

    $ touch config/elasticsearch.php
    登入後複製
  2. elasticsearch.php 配置字段映射

    <?phpreturn  [
     &#39;indices&#39; => [
         '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 [  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
    登入後複製
  2. 代码

<?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 = &#39;elasticsearch {query}&#39;;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = &#39;elasticsearch test&#39;;

    /**
     * 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();
    登入後複製

复杂自定义查询回调中的$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項目的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

適用於 Ubuntu 和 Debian 的 PHP 8.4 安裝和升級指南 適用於 Ubuntu 和 Debian 的 PHP 8.4 安裝和升級指南 Dec 24, 2024 pm 04:42 PM

PHP 8.4 帶來了多項新功能、安全性改進和效能改進,同時棄用和刪除了大量功能。 本指南介紹如何在 Ubuntu、Debian 或其衍生版本上安裝 PHP 8.4 或升級到 PHP 8.4

如何設定 Visual Studio Code (VS Code) 進行 PHP 開發 如何設定 Visual Studio Code (VS Code) 進行 PHP 開發 Dec 20, 2024 am 11:31 AM

Visual Studio Code,也稱為 VS Code,是一個免費的原始碼編輯器 - 或整合開發環境 (IDE) - 可用於所有主要作業系統。 VS Code 擁有大量針對多種程式語言的擴展,可以輕鬆編寫

您如何在PHP中解析和處理HTML/XML? 您如何在PHP中解析和處理HTML/XML? Feb 07, 2025 am 11:57 AM

本教程演示瞭如何使用PHP有效地處理XML文檔。 XML(可擴展的標記語言)是一種用於人類可讀性和機器解析的多功能文本標記語言。它通常用於數據存儲

在PHP API中說明JSON Web令牌(JWT)及其用例。 在PHP API中說明JSON Web令牌(JWT)及其用例。 Apr 05, 2025 am 12:04 AM

JWT是一種基於JSON的開放標準,用於在各方之間安全地傳輸信息,主要用於身份驗證和信息交換。 1.JWT由Header、Payload和Signature三部分組成。 2.JWT的工作原理包括生成JWT、驗證JWT和解析Payload三個步驟。 3.在PHP中使用JWT進行身份驗證時,可以生成和驗證JWT,並在高級用法中包含用戶角色和權限信息。 4.常見錯誤包括簽名驗證失敗、令牌過期和Payload過大,調試技巧包括使用調試工具和日誌記錄。 5.性能優化和最佳實踐包括使用合適的簽名算法、合理設置有效期、

php程序在字符串中計數元音 php程序在字符串中計數元音 Feb 07, 2025 pm 12:12 PM

字符串是由字符組成的序列,包括字母、數字和符號。本教程將學習如何使用不同的方法在PHP中計算給定字符串中元音的數量。英語中的元音是a、e、i、o、u,它們可以是大寫或小寫。 什麼是元音? 元音是代表特定語音的字母字符。英語中共有五個元音,包括大寫和小寫: a, e, i, o, u 示例 1 輸入:字符串 = "Tutorialspoint" 輸出:6 解釋 字符串 "Tutorialspoint" 中的元音是 u、o、i、a、o、i。總共有 6 個元

我後悔之前不知道的 7 個 PHP 函數 我後悔之前不知道的 7 個 PHP 函數 Nov 13, 2024 am 09:42 AM

如果您是經驗豐富的PHP 開發人員,您可能會感覺您已經在那裡並且已經完成了。操作

解釋PHP中的晚期靜態綁定(靜態::)。 解釋PHP中的晚期靜態綁定(靜態::)。 Apr 03, 2025 am 12:04 AM

靜態綁定(static::)在PHP中實現晚期靜態綁定(LSB),允許在靜態上下文中引用調用類而非定義類。 1)解析過程在運行時進行,2)在繼承關係中向上查找調用類,3)可能帶來性能開銷。

什麼是PHP魔術方法(__ -construct,__destruct,__call,__get,__ set等)並提供用例? 什麼是PHP魔術方法(__ -construct,__destruct,__call,__get,__ set等)並提供用例? Apr 03, 2025 am 12:03 AM

PHP的魔法方法有哪些? PHP的魔法方法包括:1.\_\_construct,用於初始化對象;2.\_\_destruct,用於清理資源;3.\_\_call,處理不存在的方法調用;4.\_\_get,實現動態屬性訪問;5.\_\_set,實現動態屬性設置。這些方法在特定情況下自動調用,提升代碼的靈活性和效率。

See all articles