Elasticsearch7.9 中国語検索の新バージョンを Laravel7 プロジェクトに簡単に統合

藏色散人
リリース: 2022-05-13 11:50:30
転載
3518 人が閲覧しました

Laravel の次のチュートリアル コラムでは、新しいバージョンの Elasticsearch7.9 中国語検索を Laravel7 プロジェクトに簡単に統合する方法を紹介します。困っている友達!


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

#たった 5 つのステップ:

#1. 統合された ik 中国語単語セグメンテーションを開始します。プラグイン Elasticsearch7.9 Docker Image

##コース推奨→:

「Elasticsearch 全文検索実戦」 (実践ビデオ)コース 「1000 万レベルのデータ同時実行ソリューション (理論的実践)」

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 公式ドキュメント

  • 統合された
  • ik 中国語単語セグメンテーションを使用する
  • プラグイン Elasticsearch

Pull 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 の詳細 elegantly

. Laravel 自体が Scout の全文検索ソリューションを提供しています. デフォルトを変更するだけで済みます Algolia ドライバーは

ElasticSearch driverElasticsearch7.9 中国語検索の新バージョンを Laravel7 プロジェクトに簡単に統合 に置き換えられます。
インストールlaravel/scout

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. 最初のタイプ:
  2. .env

    ファイルで

    SCOUT_DRIVER=Matchish\ScoutElasticSearch\Engines\ElasticSearchEngine
    ログイン後にコピー
    を指定 (推奨) #2 番目のタイプ:
  3. config/scout.php
で直接指定デフォルトのドライバーを変更します
'driver' => env('SCOUT_DRIVER', 'algolia')改为'driver' => env('SCOUT_DRIVER', 'Matchish\ScoutElasticSearch\Engines\ElasticSearchEngine')
ログイン後にコピー
  • Elasticsearch サービスの IP ポートを指定します
  • Docker デプロイメントを使用する場合は、
  • docker0# の IP を使用します##、Linux は ifconfig を通じてチェックします。
  1. .env

    ELASTICSEARCH_HOST=172.17.0.1:9200
    ログイン後にコピー

    登録サービス

    config/app で構成します。 .php

    <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">'providers' =&gt; [  // Other Service Providers  \Matchish\ScoutElasticSearch\ElasticSearchServiceProvider::class],</pre><div class="contentsignin">ログイン後にコピー</div></div>

  2. 設定キャッシュをクリア
  3. $ 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 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:learnku.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!