laravel에서 elasticsearch를 사용하는 방법을 가르쳐주세요(명확한 단계)

藏色散人
풀어 주다: 2021-10-22 09:19:42
앞으로
2397명이 탐색했습니다.

다음 튜토리얼 칼럼은 Laravel에서 laravel에서 elasticsearch를 사용하는 방법을 소개합니다(단계는 명확합니다). 모두에게 도움이 되길 바랍니다!

관련 확장 패키지 설치

  • guzzlehttp/guzzle
  • elasticsearch/elasticsearch
  • laravel/scout
  • babenkoivan/scout-elasticsearch-driver
  • predis/predis 대용량 데이터에는 대기열 동기화 사용 필요 , pull 데이터 설치 시

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에 구성 항목을 추가합니다.


elastic 템플릿 초기화

    artisan 명령을 사용하여 생성된 명령 파일 구성
  • composer require predis/predis
    로그인 후 복사
    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');
      }}
    로그인 후 복사

모델 인덱스 구성 파일 생성

Elastic searchArticleIndexConfigurator.php 작성자
php artisan make:model Models/Article
로그인 후 복사

모델 검색 규칙 파일

    ElasticsearchSearchRulesArticleRule.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_'
                  ]
              ]
          ]
      ];}
    로그인 후 복사

모델 매핑 및 검색 필드 설정
<?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,
              ],
          ],
      ];
  }}
로그인 후 복사

단계 사용

    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 유형 업데이트 Map
  • php artisan es:init
    로그인 후 복사

  • Database import etic
  • 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에서 elasticsearch를 사용하는 방법을 가르쳐주세요(명확한 단계)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:learnku.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!