美文网首页
laravel下Elasticsearch的使用 --- 20

laravel下Elasticsearch的使用 --- 20

作者: 一位先生_ | 来源:发表于2021-09-21 22:14 被阅读0次

本案例是在windows下实现
下载:elasticsearch-rtf
https://github.com/medcl/elasticsearch-analysis-ik
https://github.com/medcl/elasticsearch-rtf(下载地址,具体看下jdk环境要求)
下载完了之后将elasticsearch 放到你的项目目录下(暂时)
然后切换到bin目录下执行命令

elasticsearch 
image.png

通过elasticsearch文件下的日志文件可知道,启动成功


image.png

或者浏览器输入:
http://127.0.0.1:9200/
访问,会看到如下图,说明ok


image.png

安装 scout

composer require laravel/scout
在config/app.php 的 providers 数组中添加
Laravel\Scout\ScoutServiceProvider::class
执行命令
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider

安装 laravel-scout-elastic
composer 安装

composer require tamayo/laravel-scout-elastic
在 config/app.php 的 providers 数组中添加
ScoutEngines\Elasticsearch\ElasticsearchProvider::class

修改 scout.php 文件:

  'driver' => env('SCOUT_DRIVER', 'elasticsearch'),
     //在最后添加
     //配置elasticsearch引擎
        'elasticsearch' => [
            'index' => env('ELASTICSEARCH_INDEX', 'laravel'),//laravel就是索引的名字,可以随便起
            'hosts' => [
                env('ELASTICSEARCH_HOST', 'http://127.0.0.1:9200'),
            ],
        ]

注意:可能 composer 时可能会报错,是版本太高,实现降权 (降低版本就好)【 composer require laravel/scout ^5.0.3】

创建命令
执行命令 php artisan make:command 命令的名

php artisan make:command ESInit

会在 app\Console\Commands\ 目录下创建 ESinit.php
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 = 'Command description';
    protected $description = 'init laravel es for post';

    /**
     * Create a new command instance.
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 在这里写要写的东西
     * Execute the console command.
     * @return mixed
     */
    public function handle()
    {
        //coding,待会儿我们要在这里写代码
    }
}

在 app\Console\Kernel.php 里写

    protected $commands = [
            \App\Console\Commands\ESInit::class
        ];

composer安装guzzlehttp/guzzle

composer require guzzlehttp/guzzle 

安装 guzzlehttp/guzzle 成功后,在 ESInit.php 里的 handle () 方法里写

public function handle()
    {
        $client = new Client();
        // 创建模版
        $url = config('scout.elasticsearch.hosts')[0] . '/_template/tmp';
        $client->delete($url);//确定没有这个url

        /*
         * 这个模板作用于我要做用的索引
         * */
        $param = [
            'json'=>[
                /*
                 * 这句是取在scout.php(scout是驱动)里我们配置好elasticsearch引擎的
                 * index项。
                 * PS:其实都是取数组项,scout本身就是return一个数组,
                 * scout.elasticsearch.index就是取
                 * scout[elasticsearch][index]
                 * */
                'template'=>config('scout.elasticsearch.index'),
                'mappings'=>[
                    '_default_'=>[
                        'dynamic_templates'=>[
                            [
                                'string'=>[
                                    'match_mapping_type'=>'string',//传进来的是string
                                    'mapping'=>[
                                        'type'=>'text',//把传进来的string按text(文本)处理
                                        'analyzer'=>'ik_smart',//用ik_smart进行解析(ik是专门解析中的插件)
                                        'fields'=>[
                                            'keyword'=>[
                                                'type'=>'keyword'
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ],
            ],
        ];
        $client->put($url,$param);

        $this->info('============create template success============');

        //创建index
        $url = config('scout.elasticsearch.hosts')[0].'/'.config('scout.elasticsearch.index');
        //$client->delete($url);

        $param = [
            'json'=>[
                'settings'=>[
                    'refresh_interval'=>'5s',
                    'number_of_shards'=>1,
                    'number_of_replicas'=>0,
                ],

                'mappings'=>[
                    '_default_'=>[
                        '_all'=>[
                            'enabled'=>false
                        ]
                    ]
                ]
            ]
        ];

        $client->put($url,$param);
        $this->info('============create index success============');

    }

接着启动启动 Es

php artisan es:init
image.png

出现以上信息说明成功了!

修改你要搜索的 model,以 Post 为例:
引用命名空间

use Laravel\Scout\Searchable;

类中引用 Searchable

use Searchable;

即:


image.png

接着post,model里面重写 searchableAs () 方法 toSearchableArray () 方法

 public function searchableAs() {
        return 'post';
    }
    public function toSearchableArray() {
        return [
            'title'=>$this->title,
            'content'=>$this->content
        ];
    }

接着是导入数据处理:

php artisan scout:import "\App\Post"
image.png

测试一下:
浏览器访问:http://127.0.0.1:9200/laravel54/post/32
laravel54: 你取得索引名称,post 模型,32 文章
所以数据导入成功,无问题(这时新添加一篇文章也可以访问,说明走了索引;laravel自动处理了在这个过程)。

Post控制器调用方法,展示数据

$posts  = \App\Model\Post::search('')->get();

相关文章

网友评论

      本文标题:laravel下Elasticsearch的使用 --- 20

      本文链接:https://www.haomeiwen.com/subject/ftiigltx.html