怎么在laravel中使用elaticsearch

发布时间:2021-10-15 15:33:30 作者:iii
来源:亿速云 阅读:145

这篇文章主要讲解了“怎么在laravel中使用elaticsearch”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么在laravel中使用elaticsearch”吧!

                           

安装相关扩展包


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

创建 model 索引配置文件

创建 model 检索规则文件

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

使用步骤

使用检索

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

其他使用请自行查看文档

感谢各位的阅读,以上就是“怎么在laravel中使用elaticsearch”的内容了,经过本文的学习后,相信大家对怎么在laravel中使用elaticsearch这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

推荐阅读:
  1. 在Laravel7中如何使用UUID
  2. MongoDB怎么在Laravel中使用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

laravel

上一篇:c++基于size和rank并查集优化是怎样的

下一篇:如何解析MyBatis Mapper接受参数的四种方式代码

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》