搜索
首页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

    <?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,
                  ],
              ],
          ];
      }}

设置 model  Mapping 及检索字段

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 Template 类似 mysql 表结构

    php artisan es:init
  • 更新 elatic 类型映射

    php artisan elastic:update-mapping "App\Models\Article"
  • 数据库数据导入 elatic

    php artisan scout:import "App\Models\Article"
  • PS: 其他命令

  • 清空 elatic 数据

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

使用检索

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

其他使用请自行查看文档

以上是教你在laravel中如何使用elaticsearch(步骤分明)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:learnku。如有侵权,请联系admin@php.cn删除
Laravel(PHP)与Python:开发环境和生态系统Laravel(PHP)与Python:开发环境和生态系统Apr 12, 2025 am 12:10 AM

Laravel和Python在开发环境和生态系统上的对比如下:1.Laravel的开发环境简单,仅需PHP和Composer,提供了丰富的扩展包如LaravelForge,但扩展包维护可能不及时。2.Python的开发环境也简单,仅需Python和pip,生态系统庞大,涵盖多个领域,但版本和依赖管理可能复杂。

Laravel和后端:为Web应用程序提供动力逻辑Laravel和后端:为Web应用程序提供动力逻辑Apr 11, 2025 am 11:29 AM

Laravel是如何在后端逻辑中发挥作用的?它通过路由系统、EloquentORM、认证与授权、事件与监听器以及性能优化来简化和增强后端开发。1.路由系统允许定义URL结构和请求处理逻辑。2.EloquentORM简化数据库交互。3.认证与授权系统便于用户管理。4.事件与监听器实现松耦合代码结构。5.性能优化通过缓存和队列提高应用效率。

为什么Laravel如此受欢迎?为什么Laravel如此受欢迎?Apr 02, 2025 pm 02:16 PM

Laravel受欢迎的原因包括其简化开发过程、提供愉快的开发环境和丰富的功能。1)它吸收了RubyonRails的设计理念,结合PHP的灵活性。2)提供了如EloquentORM、Blade模板引擎等工具,提高开发效率。3)其MVC架构和依赖注入机制使代码更加模块化和可测试。4)提供了强大的调试工具和性能优化方法,如缓存系统和最佳实践。

django或laravel哪个更好?django或laravel哪个更好?Mar 28, 2025 am 10:41 AM

Django和Laravel都是全栈框架,Django适合Python开发者和复杂业务逻辑,Laravel适合PHP开发者和优雅语法。1.Django基于Python,遵循“电池齐全”哲学,适合快速开发和高并发。2.Laravel基于PHP,强调开发者体验,适合小型到中型项目。

哪个是更好的PHP或Laravel?哪个是更好的PHP或Laravel?Mar 27, 2025 pm 05:31 PM

PHP和Laravel不是直接可比的,因为Laravel是基于PHP的框架。1.PHP适合小型项目或快速原型开发,因其简单直接。2.Laravel适合大型项目或高效开发,因其提供丰富功能和工具,但学习曲线较陡,性能可能不如纯PHP。

Laravel是前端还是后端?Laravel是前端还是后端?Mar 27, 2025 pm 05:31 PM

laravelisabackendframeworkbuiltonphp,设计ForweBapplicationDevelopment.itfocusessonserver-sideLogic,databasemagemention和Applicationstructure和CanBeintegratedWithFrontendTechnologiesLikeLikeVue.jsorreActeReacterVue.jsorreActforforfull-stackDevefloct。

如何在Laravel中创建和使用自定义刀片指令?如何在Laravel中创建和使用自定义刀片指令?Mar 17, 2025 pm 02:50 PM

本文讨论了Laravel中的创建和使用自定义刀片指令以增强模板。它涵盖了定义指令,在模板中使用它们,并在大型项目中管理它们,强调了改进的代码可重复性和R等好处

如何使用Laravel的组件来创建可重复使用的UI元素?如何使用Laravel的组件来创建可重复使用的UI元素?Mar 17, 2025 pm 02:47 PM

本文讨论了使用组件在Laravel中创建和自定义可重复使用的UI元素,从而为组织提供最佳实践并建议增强包装。

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无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境