laravel使用ElasticSearch进行搜索

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lingchen__/article/details/77884753
1.安装elasticsearch和ik插件
①elasticsearch集成包(包括ik中文插件)安装地址:https://github.com/medcl/elasticsearch-rtf
②测试安装
启动elasticSearch:bin/elasticSearch -d
③测试是否安装成功
127.0.0.1:9200


2.ElasticSearch的laravel scout 包的安装
(1)①安装laravel/scout
composer require laravel/scout
②将 ScoutServiceProvider 添加到你的配置文件 config/app.php 的 providers 数组中:

Laravel\Scout\ScoutServiceProvider::class,

③注册好 Scout 的服务提供器之后,你还需使用Artisan 命令 vendor:publish 生成 Scout 的配置文件。这个命令会在你的 config 目录下生成 scout.php 配置文件:

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

(2)安装scout的es驱动(https://github.com/ErickTamayo/laravel-scout-elastic)
①composer require tamayo/laravel-scout-elastic
②You must add the Scout service provider and the package service provider in your app.php config:

// config/app.php
'providers' => [
    ...
    Laravel\Scout\ScoutServiceProvider::class,
    ...
    ScoutEngines\Elasticsearch\ElasticsearchProvider::class,
]
③Setting up Elasticsearch configuration

You must have a Elasticsearch server up and running with the index you want to use created
If you need help with this please refer to the Elasticsearch documentation
After you've published the Laravel Scout package configuration:

// config/scout.php
// Set your driver to elasticsearch
    'driver' => env('SCOUT_DRIVER', 'elasticsearch'),

...
    'elasticsearch' => [
        'index' => env('ELASTICSEARCH_INDEX', 'laravel'),
        'hosts' => [
            env('ELASTICSEARCH_HOST', 'http://localhost'),
        ],
    ],


3.创建ylaravel的索引和模板
①创建command(php artisan make:command ESInit)初始化ES
②修改ESInit.php文件(app/console/ESInit.php),同时需要先引入GuzzleHttp包
composer require Guzzlehttp/guzzle
<?php

namespace App\Console\Commands;
use GuzzleHttp\Client;
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 post';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //创建template
        $client = new Client();
        $url = config('scout.elasticsearch.hosts')[0] . '/_template/tmp';
        $client->delete($url);
        $params = [
            'json' => [
                    'template' => config('scout.elasticsearch.index'),
                ],
                'mappings' => [
                    '_default_' => [
                        'dynamic_templates' => [
                            [
                                'strings' => [
                                    'match_mapping_type' => 'string',
                                    'mapping' => [
                                        'type' => 'text',
                                        'analyzer' => 'ik_smart',
                                        'fields' => [
                                            'keyword' => [
                                                'type' => 'keyword'
                                            ]
                                        ]
                                    ]
                            ]
                        ]
                    ]
                ]
            ]
        ];
        $client->put($url, $params);

      

        // 创建index
        $url = config('scout.elasticsearch.hosts')[0] . '/' . config('scout.elasticsearch.index');
        $client->delete($url);
        $params = [
            'json' => [
                'settings' => [
                    'refresh_interval' => '5s',
                    'number_of_shards' => 1,
                    'number_of_replicas' => 0,
                ],
                'mappings' => [
                    '_default_' => [
                        '_all' => [
                            'enabled' => false
                        ]
                    ]
                ]
            ]
        ];
        $client->put($url, $params);

       
    }
}

③挂载
<?php

namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\ESInit::class
    ];

④调用es脚本
php artisan es:init

4.导入数据库和已有的数据
①修改数据模型
<?php

namespace App;

use App\Model;
use Illuminate\Database\Eloquent\Builder;
// use Laravel\Scout\Searchable;


class Posts extends Model
{
    protected $table = 'posts';

    protected $guarded = [];
    // 可以注入是的数据字段
    protected $fillable = ['title', 'content'];


    use Searchable;
     // 定义索引里面的类型
    public function searchableAs()
    {
        return 'post';
    }

     // 定义有那些字段需要搜索
     public function toSearchableArray()
    {
        return [
             'title' => $this->title,
             'content' => $this->content,
         ];
     }

②导入模型数据
php artisan scout:import "App\Posts"

导入验证
127.0.0.1:9200/laravel/54/35->记录的id

5.搜索页面和逻辑的展示

public function search()
{
	$this->validate(request(), [
		'query' => 'required'
	]);

	$query = request(['query']);

	$posts = App\Posts::search($query)->paginate(2);

	return view('post.search', compact('posts'));

}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页