使用laravel的Command实现搜索引擎索引和模板的建立

  • 创建command,初始化es

创建成功后,可通过php artisan 查看到

php artisan make:command ESInit
  • 安装guzzle

composer require guzzlehttp/guzzle
  • 配置

app/console/Commands/ESInit.php

use GuzzleHttpClient;
...
protected
$signature = 'es:init'; //以什么命令来初始化 protected $description = 'elasticsearch init command'; //描述

//实际要做的事情
public function handle()
    {
        $client = new Client();
        // 创建模版
        $url = config('scout.elasticsearch.hosts')[0] . '/_template/tmp';
        $client->delete($url);
        $client->put($url, [
            'json' => [
                'template' => config('scout.elasticsearch.index'),
                'settings' => [
                    'number_of_shards' => 1
                ],
                'mappings' => [
                    '_default_' => [
                        '_all' => [
                            'enabled' => true
                        ],
                        'dynamic_templates' => [
                            [
                                'strings' => [
                                    'match_mapping_type' => 'string',
                                    'mapping' => [
                                        'type' => 'text',
                                        'analyzer' => 'ik_smart',
                                        'ignore_above' => 256,
                                        'fields' => [
                                            'keyword' => [
                                                'type' => 'keyword'
                                            ]
                                        ]
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ]);
        $this->info('**** 创建模板成功 ****');

        $url = config('scout.elasticsearch.hosts')[0] . '/' . config('scout.elasticsearch.index');
        $client->delete($url);
        $client->put($url, [
            'json' => [
                'settings' => [
                    'refresh_interval' => '5s',
                    'number_of_shards' => 1,
                    'number_of_replicas' => 0,
                ],
                'mappings' => [
                    '_default_' => [
                        '_all' => [
                            'enabled' => false
                        ]
                    ]
                ]
            ]
        ]);
        $this->info('**** 创建index成功 ****');
    }
  • 挂载

app/console/Kernel.php

$commands = [AppConsoleCommandsESInit::class];

使用laravel的Command实现搜索引擎索引和模板的建立