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

 3299

下面给大家介绍在laravel中如何使用elaticsearch(步骤分明),希望对大家有所帮助!


安装相关扩展包

guzzlehttp/guzzle

elasticsearch/elasticsearch

laravel/scout

babenkoivan/scout-elasticsearch-driver

predis/predis 数据量大需要使用队列同步、拉取数据时安装


1、安装 guzzlehttp/guzzle

  1. composer require guzzlehttp/guzzle

在 app/Services 目录下编写 Http 服务类

  1. <?php
  2.  
  3. namespace App\Services;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Cookie\CookieJar;
  6. class HttpService
  7. {
  8.  
  9.     protected $client;
  10.  
  11.     public function __construct()
  12.     {
  13.         $this->client = new Client(['verify' => false, 'timeout' => 0,]);
  14.     }
  15.  
  16.     /**
  17.      * 发送 get 请求
  18.      * @param $url
  19.      * @param array $aQueryParam
  20.      * @param string $isDecode
  21.      * @return mixed
  22.      * @throws \GuzzleHttp\Exception\GuzzleException
  23.      */
  24.     public function get($url, $aQueryParam = [], $isDecode = true)
  25.     {
  26.         $response = $this->client->request('GET',
  27.             $url,
  28.             [
  29.                 'query' => $aQueryParam            ]);
  30.         if($isDecode){
  31.             return \GuzzleHttp\json_decode($response->getbody()->getContents(), true);
  32.         }
  33.         return $response->getbody()->getContents();
  34.     }
  35.  
  36.     /**
  37.      *  发送 post 请求
  38.      * @param $url
  39.      * @param array $aParam
  40.      * @param string $type
  41.      * @param string $isDecode
  42.      * @return mixed
  43.      * @throws \GuzzleHttp\Exception\GuzzleException
  44.      */
  45.     public function post($url, $aParam = [], $type = 'form_params', $isDecode = true)
  46.     {
  47.         $aOptions = [];
  48.         // Sending application/x-www-form-urlencoded POST
  49.         if ($type == 'form_params') {
  50.             $aOptions['form_params'] = $aParam;
  51.         }
  52.         //  upload JSON data
  53.         if ($type == 'json') {
  54.             $aOptions['json'] = $aParam;
  55.         }
  56.         $response = $this->client->request('POST', $url, $aOptions);
  57.  
  58.         if($isDecode){
  59.             return \GuzzleHttp\json_decode($response->getbody()->getContents(), true);
  60.         }
  61.         return $response->getbody()->getContents();
  62.     }
  63.  
  64.     /**
  65.      *  发送 put 请求
  66.      * @param $url
  67.      * @param array $aParam
  68.      * @param string $type
  69.      * @param string $isDecode
  70.      * @return mixed
  71.      * @throws \GuzzleHttp\Exception\GuzzleException
  72.      */
  73.     public function put($url, $aParam = [], $type = 'form_params', $isDecode = true)
  74.     {
  75.         $aOptions = [];
  76.         // Sending application/x-www-form-urlencoded POST
  77.         if ($type == 'form_params') {
  78.             $aOptions['form_params'] = $aParam;
  79.         }
  80.         //  upload JSON data
  81.         if ($type == 'json') {
  82.             $aOptions['json'] = $aParam;
  83.         }
  84.         $response = $this->client->request('PUT', $url, $aOptions);
  85.  
  86.         if($isDecode){
  87.             return \GuzzleHttp\json_decode($response->getbody()->getContents(), true);
  88.         }
  89.         return $response->getbody()->getContents();
  90.     }
  91.  
  92.     /**
  93.      * 保存远程文件到本地
  94.      * 跟随第三方服务器url重定向
  95.      * @param $url
  96.      * @return bool|string
  97.      */
  98.     public function getRemoteFile($url)
  99.     {
  100.         $jar = new CookieJar();
  101.         $aOptions = ['cookies' => $jar];
  102.         $response = $this->client->request('GET', $url, $aOptions);
  103.         return $response->getBody()->getContents();
  104.     }
  105. }


2、安装 elasticsearch/elasticsearch

  1. composer require elasticsearch/elasticsearch


3、安装 laravel/scout

  1. composer require laravel/scout 
  2. php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"


4、安装 scout 第三方驱动 babenkoivan/scout-elasticsearch-driver

  1. composer require babenkoivan/scout-elasticsearch-driver 
  2. php artisan vendor:publish --provider="ScoutElastic\ScoutElasticServiceProvider"

scout 服务配置,在 env 中增加配置项

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


5、安装 predis/predis

  1. composer require predis/predis


初始化 elatic Template

这里以 artisan 命令的方式配置 生成命令文件

  1. php artisan make:command EsInit
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Services\HttpService;
  4. use Illuminate\Console\Command;
  5. class EsInit extends Command
  6. {
  7.     /**
  8.      * The name and signature of the console command.
  9.      *
  10.      * @var string
  11.      */
  12.     protected $signature = 'es:init';
  13.  
  14.     /**
  15.      * The console command description.
  16.      *
  17.      * @var string
  18.      */
  19.     protected $description = 'init laravel es for article';
  20.  
  21.     /**
  22.      * Create a new command instance.
  23.      *
  24.      * @return void
  25.      */
  26.     protected  $http;
  27.     public function __construct()
  28.     {
  29.         parent::__construct();
  30.         parent::__construct();
  31.         $this->http = new HttpService();
  32.     }
  33.  
  34.     /**
  35.      * Execute the console command.
  36.      *
  37.      * @return mixed
  38.      */
  39.     public function handle()
  40.     {
  41.         $this->createTemplate();
  42.     }
  43.     protected function createTemplate()
  44.     {
  45.         $aData = [
  46.             /*
  47.              * 这句是取在scout.php(scout是驱动)里我们配置好elasticsearch引擎的index项。
  48.              * PS:其实都是取数组项,scout本身就是return一个数组,
  49.              * scout.elasticsearch.index就是取
  50.              * scout[elasticsearch][index]
  51.              **/
  52.             'template'=>config('scout.elasticsearch.index'),
  53.             'mappings'=>[
  54.                 'articles' => [
  55.                     'properties' => [
  56.                         'title' => [
  57.                             'type' => 'text'
  58.                         ],
  59.                         'content' => [
  60.                             'type' => 'text'
  61.                         ],
  62.                         'created_at' => [
  63.                             'format' => 'yy-MM-dd HHss',
  64.                             'type' => 'date'
  65.                         ],
  66.                         'updated_at' => [
  67.                             'format' => 'yy-MM-dd HHss',
  68.                             'type' => 'date'
  69.                         ]
  70.                     ]
  71.                 ]
  72.             ],
  73.         ];
  74.         $url = config('scout.elasticsearch.hosts')[0] . '/' . '_template/rtf';
  75.         $this->http->put($url,$aData,'json');
  76.     }
  77. }

生成检索 model

  1. php artisan make:model Models/Article


创建 model 索引配置文件

Elasticsearch\ArticleIndexConfigurator.php

  1. <?php
  2. namespace App\Elasticsearch;
  3. use ScoutElastic\IndexConfigurator;
  4. use ScoutElastic\Migratable;
  5. class ArticleIndexConfigurator extends IndexConfigurator
  6. {
  7.     use Migratable;
  8.     protected $name = 'articles';
  9.     /**
  10.      * @var array
  11.      */
  12.     protected $settings = [
  13.         'analysis' => [
  14.             'analyzer' => [
  15.                 'es_std' => [
  16.                     'type' => 'standard',
  17.                     'stopwords' => '_spanish_'
  18.                 ]
  19.             ]
  20.         ]
  21.     ];
  22. }


创建 model 检索规则文件

Elasticsearch\SearchRules\ArticleRule.php

  1. <?php
  2. namespace App\Elasticsearch\SearchRules;
  3. use ScoutElastic\SearchRule;
  4. class ArticleRule extends SearchRule
  5. {
  6.     /*
  7.      * @inheritdoc
  8.      */
  9.     public function buildHighlightPayload()
  10.     {
  11.         return [
  12.             'fields' => [
  13.                 'title' => [
  14.                     'type' => 'unified',
  15.                 ],
  16.                 'content' => [
  17.                     'type' => 'unified',
  18.                 ],
  19.             ]
  20.         ];
  21.     }
  22.  
  23.     //进行 match 搜索,会分词
  24.     public function buildQueryPayload()
  25.     {
  26.         $query = $this->builder->query;
  27.         return [
  28.             'must' => [
  29.                 'query_string' => [
  30.                     'query' => $query,
  31.                 ],
  32.             ],
  33.         ];
  34.     }
  35. }


设置 model Mapping 及检索字段

  1. class Article extends Model{
  2.     protected $indexConfigurator = ArticleIndexConfigurator::class;
  3.     use Searchable;
  4.  
  5.     /**
  6.      * 检索规则
  7.      * @var string[]
  8.      */
  9.     protected $searchRules = [
  10.         ArticleRule::class
  11.     ];
  12.  
  13.     // 设置模型字段的映射关系
  14.     protected $mapping = [
  15.         'properties' => [
  16.             'id' => [
  17.                 'type' => 'integer',
  18.             ],
  19.             'title' => [
  20.                 'type' => 'text',
  21.                 'analyzer' => 'ik_max_word',
  22.                 'search_analyzer' => 'ik_max_word',
  23.                 'index_options' => 'offsets',
  24.                 'store' => true
  25.             ],
  26.             'content' => [
  27.                 'type' => 'text',
  28.                 'analyzer' => 'ik_max_word',
  29.                 'search_analyzer' => 'ik_max_word',
  30.                 'index_options' => 'offsets',
  31.                 'store' => true
  32.             ],
  33.             'number' => [
  34.                 'type' => 'integer',
  35.             ],
  36.         ],
  37.     ];
  38.  
  39.     /**
  40.      * 设置 es 检索返回的字段
  41.      * [@return](https://learnku.com/users/31554) array
  42.      */
  43.     public function toSearchableArray() {
  44.         return [
  45.             'id' => $this->id,
  46.             'title' => $this->title,
  47.             'content' => $this->content,
  48.         ];
  49.     }
  50. }


使用步骤

生成 elatic Template 类似 mysql 表结构

  1. php artisan es:init

更新 elatic 类型映射

  1. php artisan elastic:update-mapping "App\Models\Article"

数据库数据导入 elatic

  1. php artisan scout:import "App\Models\Article"


PS: 其他命令

清空 elatic 数据

  1. php artisan scout:flush "App\Models\Article"

使用检索

  1. $query = Article::search('二胡')
  2.         ->paginateRaw(3,'article',1);
  3. dd($query->items()['hits']);

其他使用请自行查看文档


本文网址:https://www.zztuku.com/index.php/detail-9630.html
站长图库 - 教你在laravel中如何使用elaticsearch(步骤分明)
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐