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

教你在laravel如何使用elaticsearch(步驟分明)

Oct 15, 2021 pm 03:24 PM
laravel

以下由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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡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脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

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

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

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

在Laravel中如何獲取郵件發送失敗時的退信代碼? 在Laravel中如何獲取郵件發送失敗時的退信代碼? Apr 01, 2025 pm 02:45 PM

Laravel郵件發送失敗時的退信代碼獲取方法在使用Laravel開發應用時,經常會遇到需要發送驗證碼的情況。而在實�...

Bangla 部分模型檢索中的 Laravel Eloquent ORM) Bangla 部分模型檢索中的 Laravel Eloquent ORM) Apr 08, 2025 pm 02:06 PM

LaravelEloquent模型檢索:輕鬆獲取數據庫數據EloquentORM提供了簡潔易懂的方式來操作數據庫。本文將詳細介紹各種Eloquent模型檢索技巧,助您高效地從數據庫中獲取數據。 1.獲取所有記錄使用all()方法可以獲取數據庫表中的所有記錄:useApp\Models\Post;$posts=Post::all();這將返回一個集合(Collection)。您可以使用foreach循環或其他集合方法訪問數據:foreach($postsas$post){echo$post->

laravel入門實例 laravel入門實例 Apr 18, 2025 pm 12:45 PM

Laravel 是一款 PHP 框架,用於輕鬆構建 Web 應用程序。它提供一系列強大的功能,包括:安裝: 使用 Composer 全局安裝 Laravel CLI,並在項目目錄中創建應用程序。路由: 在 routes/web.php 中定義 URL 和處理函數之間的關係。視圖: 在 resources/views 中創建視圖以呈現應用程序的界面。數據庫集成: 提供與 MySQL 等數據庫的開箱即用集成,並使用遷移來創建和修改表。模型和控制器: 模型表示數據庫實體,控制器處理 HTTP 請求。

Laravel的地理空間:互動圖和大量數據的優化 Laravel的地理空間:互動圖和大量數據的優化 Apr 08, 2025 pm 12:24 PM

利用地理空間技術高效處理700萬條記錄並創建交互式地圖本文探討如何使用Laravel和MySQL高效處理超過700萬條記錄,並將其轉換為可交互的地圖可視化。初始挑戰項目需求:利用MySQL數據庫中700萬條記錄,提取有價值的見解。許多人首先考慮編程語言,卻忽略了數據庫本身:它能否滿足需求?是否需要數據遷移或結構調整? MySQL能否承受如此大的數據負載?初步分析:需要確定關鍵過濾器和屬性。經過分析,發現僅少數屬性與解決方案相關。我們驗證了過濾器的可行性,並設置了一些限制來優化搜索。地圖搜索基於城

解決 Craft CMS 中的緩存問題:使用 wiejeben/craft-laravel-mix 插件 解決 Craft CMS 中的緩存問題:使用 wiejeben/craft-laravel-mix 插件 Apr 18, 2025 am 09:24 AM

在使用CraftCMS開發網站時,常常會遇到資源文件緩存的問題,特別是當你頻繁更新CSS和JavaScript文件時,舊版本的文件可能仍然被瀏覽器緩存,導致用戶無法及時看到最新的更改。這個問題不僅影響用戶體驗,還會增加開發和調試的難度。最近,我在項目中遇到了類似的困擾,經過一番探索,我找到了wiejeben/craft-laravel-mix這個插件,它完美地解決了我的緩存問題。

laravel用戶登錄功能 laravel用戶登錄功能 Apr 18, 2025 pm 12:48 PM

Laravel 提供了一個全面的 Auth 框架,用於實現用戶登錄功能,包括:定義用戶模型(Eloquent 模型)創建登錄表單(Blade 模板引擎)編寫登錄控制器(繼承 Auth\LoginController)驗證登錄請求(Auth::attempt)登錄成功後重定向(redirect)考慮安全因素:哈希密碼、防 CSRF 保護、速率限制和安全標頭。此外,Auth 框架還提供重置密碼、註冊和驗證電子郵件等功能。詳情請參閱 Laravel 文檔:https://laravel.com/doc

Laravel和後端:為Web應用程序提供動力邏輯 Laravel和後端:為Web應用程序提供動力邏輯 Apr 11, 2025 am 11:29 AM

Laravel是如何在後端邏輯中發揮作用的?它通過路由系統、EloquentORM、認證與授權、事件與監聽器以及性能優化來簡化和增強後端開發。 1.路由系統允許定義URL結構和請求處理邏輯。 2.EloquentORM簡化數據庫交互。 3.認證與授權系統便於用戶管理。 4.事件與監聽器實現松耦合代碼結構。 5.性能優化通過緩存和隊列提高應用效率。

laravel框架安裝方法 laravel框架安裝方法 Apr 18, 2025 pm 12:54 PM

文章摘要:本文提供了詳細分步說明,指導讀者如何輕鬆安裝 Laravel 框架。 Laravel 是一個功能強大的 PHP 框架,它 упростил 和加快了 web 應用程序的開發過程。本教程涵蓋了從系統要求到配置數據庫和設置路由等各個方面的安裝過程。通過遵循這些步驟,讀者可以快速高效地為他們的 Laravel 項目打下堅實的基礎。

See all articles