搜尋
首頁php框架Laravel教你在laravel如何使用elaticsearch(步驟分明)

以下由Laravel教學專欄帶大家介紹在laravel如何使用elaticsearch(步驟分明),希望對大家有幫助!

安裝相關擴充包

  • guzzlehttp/guzzle
  • elasticsearch/elasticsearch
  • #laravel /scout
  • babenkoivan/scout-elasticsearch-driver
  • predis/predis  資料量大需要使用佇列同步、拉取資料時安裝

#1.安裝guzzlehttp/guzzle

composer require guzzlehttp/guzzle

#在app/Services 目錄下編寫Http 服務類別

<?php namespace App\Services;use GuzzleHttp\Client;use GuzzleHttp\Cookie\CookieJar;class HttpService{

    protected $client;

    public function __construct()
    {
        $this->client = new Client(['verify' => false, 'timeout' => 0,]);
    }

    /**
     * 发送 get 请求
     * @param $url
     * @param array $aQueryParam
     * @param string $isDecode
     * [@return](https://learnku.com/users/31554) mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function get($url, $aQueryParam = [], $isDecode = true)
    {
        $response = $this->client->request('GET',
            $url,
            [
                'query' => $aQueryParam            ]);
        if($isDecode){
            return \GuzzleHttp\json_decode($response->getbody()->getContents(), true);
        }
        return $response->getbody()->getContents();
    }

    /**
     *  发送 post 请求
     * @param $url
     * @param array $aParam
     * @param string $type
     * @param string $isDecode
     * [@return](https://learnku.com/users/31554) mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function post($url, $aParam = [], $type = 'form_params', $isDecode = true)
    {
        $aOptions = [];
        // Sending application/x-www-form-urlencoded POST
        if ($type == 'form_params') {
            $aOptions['form_params'] = $aParam;
        }
        //  upload JSON data
        if ($type == 'json') {
            $aOptions['json'] = $aParam;
        }
        $response = $this->client->request('POST', $url, $aOptions);

        if($isDecode){
            return \GuzzleHttp\json_decode($response->getbody()->getContents(), true);
        }
        return $response->getbody()->getContents();
    }

    /**
     *  发送 put 请求
     * @param $url
     * @param array $aParam
     * @param string $type
     * @param string $isDecode
     * [@return](https://learnku.com/users/31554) mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function put($url, $aParam = [], $type = 'form_params', $isDecode = true)
    {
        $aOptions = [];
        // Sending application/x-www-form-urlencoded POST
        if ($type == 'form_params') {
            $aOptions['form_params'] = $aParam;
        }
        //  upload JSON data
        if ($type == 'json') {
            $aOptions['json'] = $aParam;
        }
        $response = $this->client->request('PUT', $url, $aOptions);

        if($isDecode){
            return \GuzzleHttp\json_decode($response->getbody()->getContents(), true);
        }
        return $response->getbody()->getContents();
    }

    /**
     * 保存远程文件到本地
     * 跟随第三方服务器url重定向
     * @param $url
     * [@return](https://learnku.com/users/31554) bool|string
     */
    public function getRemoteFile($url)
    {
        $jar = new CookieJar();
        $aOptions = ['cookies' => $jar];
        $response = $this->client->request('GET', $url, $aOptions);
        return $response->getBody()->getContents();
    }}

#2.安裝elasticsearch/elasticsearch

composer require elasticsearch/elasticsearch

3.安裝laravel/scout

composer require laravel/scout

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

4.安裝scout 第三方驅動程式babenkoivan/scout-elasticsearch-driver

composer require babenkoivan/scout-elasticsearch-driver

php artisan vendor:publish --provider="ScoutElastic\ScoutElasticServiceProvider"

scout 服務配置,在env 中增加配置項目

// 驱动的host,若需账密:http://es_username:password@127.0.0.1:9200SCOUT_ELASTIC_HOST=elasticsearch:9200// 驱动SCOUT_DRIVER=elastic// 队列配置,数据量大时建议开启SCOUT_QUEUE=true

5.安裝predis/predis

composer require predis/predis

#初始化elatic Template

  • 這裡以artisan 指令的方式設定產生指令檔

    php artisan make:command EsInit
    <?php namespace App\Console\Commands;use App\Services\HttpService;use Illuminate\Console\Command;class EsInit extends Command{
      /**
       * The name and signature of the console command.
       *
       * @var string
       */
      protected $signature = &#39;es:init&#39;;
    
      /**
       * The console command description.
       *
       * @var string
       */
      protected $description = &#39;init laravel es for article&#39;;
    
      /**
       * Create a new command instance.
       *
       * [@return](https://learnku.com/users/31554) void
       */
      protected  $http;
      public function __construct()
      {
          parent::__construct();
          parent::__construct();
          $this->http = new HttpService();
      }
    
      /**
       * Execute the console command.
       *
       * [@return](https://learnku.com/users/31554) mixed
       */
      public function handle()
      {
          $this->createTemplate();
      }
      protected function createTemplate()
      {
          $aData = [
              /*
              * 这句是取在scout.php(scout是驱动)里我们配置好elasticsearch引擎的index项。
              * PS:其实都是取数组项,scout本身就是return一个数组,
              * scout.elasticsearch.index就是取
              * scout[elasticsearch][index]
              * */
              'template'=>config('scout.elasticsearch.index'),
              'mappings'=>[
                  'articles' => [
                      'properties' => [
                          'title' => [
                              'type' => 'text'
                          ],
                          'content' => [
                              'type' => 'text'
                          ],
                          'created_at' => [
                              'format' => 'yy-MM-dd HHss',
                              'type' => 'date'
                          ],
                          'updated_at' => [
                              'format' => 'yy-MM-dd HHss',
                              'type' => 'date'
                          ]
                      ]
                  ]
              ],
          ];
          $url = config('scout.elasticsearch.hosts')[0] . '/' . '_template/rtf';
          $this->http->put($url,$aData,'json');
      }}

    產生檢索model

    #
    php artisan make:model Models/Article

建立model 索引設定檔

  • Elasticsearch\ArticleIndexConfigurator.php
    <?php namespace App\Elasticsearch;use ScoutElastic\IndexConfigurator;use ScoutElastic\Migratable;class ArticleIndexConfigurator extends IndexConfigurator{
      use Migratable;
      protected $name = &#39;articles&#39;;
      /**
       * @var array
       */
      protected $settings = [
          &#39;analysis&#39; => [
              'analyzer' => [
                  'es_std' => [
                      'type' => 'standard',
                      'stopwords' => '_spanish_'
                  ]
              ]
          ]
      ];}

建立model 檢索規則檔案

  • Elasticsearch\SearchRules\ArticleRule.php

  • ##Elasticsearch\SearchRules\ArticleRule.php

設定model  Mapping 及擷取欄位
<?php namespace App\Elasticsearch\SearchRules;use ScoutElastic\SearchRule;class ArticleRule extends SearchRule{
  /*
   * @inheritdoc
   */
  public function buildHighlightPayload()
  {
      return [
          &#39;fields&#39; => [
              'title' => [
                  'type' => 'unified',
              ],
              'content' => [
                  'type' => 'unified',
              ],
          ]
      ];
  }

  //进行 match 搜索,会分词
  public function buildQueryPayload()
  {
      $query = $this->builder->query;
      return [
          'must' => [
              'query_string' => [
                  'query' => $query,
              ],
          ],
      ];
  }}

    使用步驟
  • 產生elatic Template 類似mysql 表格結構
  • class Article extends Model{
        protected $indexConfigurator = ArticleIndexConfigurator::class;
        use Searchable;
    
        /**
         * 检索规则
         * @var string[]
         */
        protected $searchRules = [
            ArticleRule::class
        ];
    
        // 设置模型字段的映射关系
        protected $mapping = [
            'properties' => [
                'id' => [
                    'type' => 'integer',
                ],
                'title' => [
                    'type' => 'text',
                    'analyzer' => 'ik_max_word',
                    'search_analyzer' => 'ik_max_word',
                    'index_options' => 'offsets',
                    'store' => true
                ],
                'content' => [
                    'type' => 'text',
                    'analyzer' => 'ik_max_word',
                    'search_analyzer' => 'ik_max_word',
                    'index_options' => 'offsets',
                    'store' => true
                ],
                'number' => [
                    'type' => 'integer',
                ],
            ],
        ];
    
        /**
         * 设置 es 检索返回的字段
         * [@return](https://learnku.com/users/31554) array
         */
        public function toSearchableArray() {
            return [
                'id' => $this->id,
                'title' => $this->title,
                'content' => $this->content,
            ];
        }}

  • 更新elatic 類型對應
  • #
    php artisan es:init

  • 資料庫資料導入elatic
  • php artisan elastic:update-mapping "App\Models\Article"

  • PS:其他指令
  • 清除elatic 資料
php artisan scout:import "App\Models\Article"

使用檢索
php artisan scout:flush "App\Models\Article"

###其他使用請自行檢視文件###

以上是教你在laravel如何使用elaticsearch(步驟分明)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:learnku。如有侵權,請聯絡admin@php.cn刪除
使用Laravel:使用PHP簡化Web開發使用Laravel:使用PHP簡化Web開發Apr 19, 2025 am 12:18 AM

Laravel優化Web開發流程的方法包括:1.使用路由系統管理URL結構;2.利用Blade模板引擎簡化視圖開發;3.通過隊列處理耗時任務;4.使用EloquentORM簡化數據庫操作;5.遵循最佳實踐提高代碼質量和可維護性。

Laravel:PHP Web框架的簡介Laravel:PHP Web框架的簡介Apr 19, 2025 am 12:15 AM

Laravel是一個現代化的PHP框架,提供了強大的工具集,簡化了開發流程並提高了代碼的可維護性和可擴展性。 1)EloquentORM簡化數據庫操作;2)Blade模板引擎使前端開發直觀;3)Artisan命令行工具提升開發效率;4)性能優化包括使用EagerLoading、緩存機制、遵循MVC架構、隊列處理和編寫測試用例。

Laravel:MVC建築和最佳實踐Laravel:MVC建築和最佳實踐Apr 19, 2025 am 12:13 AM

Laravel的MVC架構通過模型、視圖、控制器分離數據邏輯、展示和業務處理,提高了代碼的結構化和可維護性。 1)模型處理數據,2)視圖負責展示,3)控制器處理用戶輸入和業務邏輯,這種架構讓開發者專注於業務邏輯,避免陷入代碼泥潭。

Laravel:解釋的主要功能和優勢Laravel:解釋的主要功能和優勢Apr 19, 2025 am 12:12 AM

Laravel是一個基於MVC架構的PHP框架,具有簡潔的語法、強大的命令行工具、便捷的數據操作和靈活的模板引擎。 1.優雅的語法和易用的API使開發快速上手。 2.Artisan命令行工具簡化了代碼生成和數據庫管理。 3.EloquentORM讓數據操作直觀簡單。 4.Blade模板引擎支持高級視圖邏輯。

用Laravel建造後端:指南用Laravel建造後端:指南Apr 19, 2025 am 12:02 AM

Laravel適合構建後端服務,因為它提供了優雅的語法、豐富的功能和強大的社區支持。 1)Laravel基於MVC架構,簡化了開發流程。 2)它包含EloquentORM,優化了數據庫操作。 3)Laravel的生態系統提供瞭如Artisan、Blade和路由系統等工具,提升開發效率。

laravel框架技巧分享laravel框架技巧分享Apr 18, 2025 pm 01:12 PM

在這個技術不斷進步的時代,掌握先進的框架對於現代程序員至關重要。本文將通過分享 Laravel 框架中鮮為人知的技巧,幫助你提升開發技能。 Laravel 以其優雅的語法和廣泛的功能而聞名,本文將深入探討其強大的特性,提供實用技巧和竅門,幫助你打造高效且維護性高的 Web 應用程序。

laravel和thinkphp的區別laravel和thinkphp的區別Apr 18, 2025 pm 01:09 PM

Laravel 和 ThinkPHP 都是流行的 PHP 框架,在開發中各有優缺點。本文將深入比較這兩者,重點介紹它們的架構、特性和性能差異,以幫助開發者根據其特定項目需求做出明智的選擇。

laravel用戶登錄功能一覽laravel用戶登錄功能一覽Apr 18, 2025 pm 01:06 PM

在 Laravel 中構建用戶登錄功能是一個至關重要的任務,本文將提供一個全面的概述,涵蓋從用戶註冊到登錄驗證的每個關鍵步驟。我們將深入探討 Laravel 的內置驗證功能的強大功能,並指導您自定義和擴展登錄過程以滿足特定需求。通過遵循這些一步一步的說明,您可以創建安全可靠的登錄系統,為您的 Laravel 應用程序的用戶提供無縫的訪問體驗。

See all articles

熱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 無盡。

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具