• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • dedecms
  • ecshop
  • z-blog
  • UcHome
  • UCenter
  • drupal
  • WordPress
  • 帝国cms
  • phpcms
  • 动易cms
  • phpwind
  • discuz
  • 科汛cms
  • 风讯cms
  • 建站教程
  • 运营技巧
您的位置:首页 > CMS教程 >建站教程 > 教你在laravel中如何使用elaticsearch(步骤分明)

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

作者:站长图库 字体:[增加 减小] 来源:互联网 时间:2022-04-29

站长图库向大家介绍了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 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 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 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 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
<?phpnamespace 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 = 'es:init';     /**     * The console command description.     *     * @var string     */    protected $description = 'init laravel es for article';     /**     * Create a new command instance.     *     * @return void     */    protected  $http;    public function __construct()    {        parent::__construct();        parent::__construct();        $this->http = new HttpService();    }     /**     * Execute the console command.     *     * @return 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

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


创建 model 检索规则文件

Elasticsearch\SearchRules\ArticleRule.php

<?phpnamespace App\Elasticsearch\SearchRules;use ScoutElastic\SearchRule;class ArticleRule extends SearchRule{    /*     * @inheritdoc     */    public function buildHighlightPayload()    {        return [            'fields' => [                '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']);

其他使用请自行查看文档


分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

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

相关文章

  • 2022-04-29怎样利用PHP+Mysql实现基本的增删改查功能?(实例详解)
  • 2022-04-29vue.js如何实现可拖拽菜单
  • 2022-04-29PHP在图片中用 imagettftext() 添加水印(图文详解)
  • 2022-04-29ThinkPHP5框架实现多数据库连接
  • 2022-04-29ThinkPHP如何使用migrate实现数据库迁移
  • 2022-04-29PhotoShop+coreldRAW打造喜迎国庆节海报制作教程
  • 2022-04-29PHP网站常见安全漏洞,及相应防范措施总结
  • 2022-04-29PS绘制精致陌陌图标
  • 2022-04-29使用css实现自适应标题浮动效果(代码实例)
  • 2022-04-29SEO优化-百度规则解析

文章分类

  • dedecms
  • ecshop
  • z-blog
  • UcHome
  • UCenter
  • drupal
  • WordPress
  • 帝国cms
  • phpcms
  • 动易cms
  • phpwind
  • discuz
  • 科汛cms
  • 风讯cms
  • 建站教程
  • 运营技巧

最近更新的内容

    • composer下composer.lock的用处及删除它的方法
    • vue.js如何实现数字滚动增加效果?代码示例
    • 新站如何得到搜索引擎的好感?
    • Photoshop制作时尚绚丽的3D立体字教程
    • javascript怎么判断是否为null
    • PHP中如何将JSON文件转XML格式
    • ThinkPHP3.2.3如何从php5升级到php7
    • Photoshop绘制十二生肖按钮图标教程
    • 网站SEO第一步:忘掉你的目标关键词
    • 如何使用thinkphp5.1的数组查询对象

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有