laravel使用ElasticSearch進行搜索

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'));

}

發佈了48 篇原創文章 · 獲贊 32 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章