一 簡介php
laravel 的組件化使 laravel 的使用更加駕輕就熟。java
Laravel Scout 爲 Eloquent 模型 全文搜索提供了簡單的,基於驅動的解決方案。經過使用模型觀察者,Scout 會自動同步 Eloquent 記錄的搜索索引。laravel
簡單的來講 Scout 是用來全文檢索的一個組件(不具備搜索功能),它使用驅動來調用搜索引擎來進行搜索。這裏講解 laravel 使用 elasticsearch 搜索引擎。git
在已有的項目中要想使用 elsaticsearch 搜索引擎,須要四個步驟:github
1.給項目 compoer 安裝 Scout 2.給項目 composer 安裝 elasticsearch 驅動 數據庫
3.給服務器安裝 elasticsearch 搜索引擎 4.在項目中創建 elasticsearch 索引和模板json
1 和 2 使用 composer 來安裝,3 咱們使用GitHub上別人作的集成包,裏面有個 ik 插件,是用來優化中文檢索,elasticsearch 只是搜索引擎,而對搜索的實際效果是靠插件來進行的。ik 中文搜索靠的是詞意解析,中華人民共和國國歌,精確解析:中華人民共和國、中華、華人、人民、共和國、國歌,粗糙解析:中華人民共和國、國歌。解析的效果不一樣。windows
下面給出帶有 ik 插件的 elastsearch 集成包:https://github.com/medcl/elasticsearch-rtf 瀏覽器
二 安裝步驟
服務器
1.安裝 elasticsearch 搜索引擎到服務器
下載上面的集成包,Download ZIP,在服務器上進行解壓(windows測試練習一樣步驟、下載解壓)
下載 java1.8 安裝和配置環境變量(這裏不講解,百度大把教程,已經安裝的繼續)
打開解壓的文件夾到 bin 下,可使用 ls 查看bin下的文件( windows下命令行使用 dir 查看 )
有一個 elasticsearch 和 elasticsearch.bat ,這時候咱們啓動 elasticsearch
方法是輸入:elasticsearch -d ( windows下命令行裏輸入 elasticsearch.bat -d ),這樣子就能夠啓動成功
啓動會顯示日誌,能夠看到有 127.0.0.1:9200 既是啓動成功,能夠在瀏覽器輸入這個 ip加端口,會看到一個 json 信息。
在服務器搭建的時候,必定要啓動而且守護進程。bin 下還有一個文件是 elasticsearch-plugin
可使用 elasticsearch-plugin list 來查看搜索引擎的插件,其中一個既是咱們要使用的 ik 中文檢索插件。
2. 安裝Scout
進入到項目裏面,使用:composer require laravel/scout 來安裝Scout
安裝完成後再次輸入:php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
這個目的是把 Scout.php 配置文件從 vendor 中提取到 config 中,進行 Scout 配置
接下來把 Scout 服務提供者放入 app.php 配置文件中,在 providers 中插入:Laravel\Scout\ScoutServiceProvider::class
這樣子 Scout 就安裝完了
3. 安裝elasticsearch
在進行搜索的時候,Scout 經過 elasticsearch 驅動,來調用 elasticsearch 搜索引擎,搜索引擎經過 ik 插件,進行解析並返回數據。
安裝驅動經過 composer 安裝,終端( 或者命令行 )打開項目輸入:composer require tamayo/laravel-scout-elastic
安裝完成後,到 app.php 配置文件中註冊服務提供者,在 providers 中插入:ScoutEngines\Elasticsearch\ElasticsearchProvider::class
插入完成後,到 Scout.php 配置文件中,配置 Scout 的驅動爲 elasticsearch
將驅動的默認值改成elasticsearch,在配置文件中找到這一段並修改 'driver' => env('SCOUT_DRIVER', 'elasticsearch')
在下方插入 elasticsearch 驅動的配置,其意思爲,elasticsearch 的索引名爲 laravel ,能夠本身修改,它的 ip 地址爲本服務器的 9200 端口:
'elasticsearch' => [ 'index' => env('ELASTICSEARCH_INDEX', 'post'), 'hosts' => [ env('ELASTICSEARCH_HOST', 'http://127.0.0.1:9200'), ], ],
在這裏,索引的名稱不能使用laravel,不然後面會報錯,換個名稱,這裏我使用post,這樣,驅動就安裝配置完成
4. elasticsearch 的索引和模板創建
使用 Artisan 建立一個自定義 command 命令,這個命令用來初始化建立索引和模板。
建立 command 的方法:php artisan make:command ESinit 給這個命令取名爲ESinit,意思爲初始化ES
建立好了,在 app 下的 Console 中會生成文件夾 Commands,這個文件夾存放自定義的 artisan 命令,咱們能夠到看 ESinit.php
在這個文件中有兩個屬性和兩個方法,屬性爲命令名稱和描述,方法爲一個構造函數和一個 handle 句柄函數。
修改兩個屬性,第一個爲:es:init ,意思爲在咱們建立好了這個命令的時候,就可使用 php artisan es:init 來執行 handle 行爲去建立模板與索引
第二個爲這個命令的描述,用來告訴使用者,這個命令是用來幹嘛,修改成:init laravel es for model ,意思爲初始化 laravel 的 es 搜索對某個模型
接下就要進行 handle 行爲編寫,第一個是編寫 template 模板,第二個是編寫 index 索引,如何去建立模板與索引。
使用restful風格的 http 請求,往 ES搜索引擎發送 http 請求,須要引入一個類庫:GuzzleHttp\Client ,
安裝這個類使用 composer :composer require guzzlehttp/guzzle 安裝好後,在 ESinit.php 中 user GuzzleHttp\Client;
接下來在 handle 中編寫行爲,比較複雜,直接貼上來:
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 model'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $client = new Client(); // 建立模版 $url = config('scout.elasticsearch.hosts')[0] . '/_template/tmp'; $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->put($url, [ 'json' => [ 'settings' => [ 'refresh_interval' => '5s', 'number_of_shards' => 1, 'number_of_replicas' => 0, ], 'mappings' => [ '_default_' => [ '_all' => [ 'enabled' => false ] ] ] ] ]); $this->info("=====建立索引成功====="); } }
簡單說明:實例化Client這個類,而後建立模板和索引的url,分別像url插入數據。索引用來存放被查詢的文章,模板用來放查詢的規則
每次查詢都是在搜索引擎去調用索引查詢,而不是去數據庫中查詢,這方面的只是能夠到 elasticsearch 官網查看相關文檔。
在完成 handle 行爲的編寫,就能夠把這個自定義命令掛載到 artisan 中,在 app 下的 Console 下的 Kernel.php 中的 commands 屬性中加上
\App\Console\Commands\ESinit::class 這段代碼便可完成掛載。
編寫完成了,在命令行輸入:php artisan es:init 這樣子就建立完成了。
5. 修改模型、導入數據到索引
在要搜索的模型中 use Laravel\Scout\Searchable;
定義兩個方法,直接貼上來:
use Searchable; //定義索引裏的type值 public function searchableAs() { return 'post'; } //定義要查詢的字段 public function toSearchableArray() { return [ 'title' => $this->title, 'content' => $this->content ]; }
定義好了這兩個方法,須要導入模型數據到索引中。
使用 artisan 命令:php artisan scout:import 'App\Post' 使用此方法須要帶個模型,既把這個模型的數據存入索引中,在這裏遇到問題
須要安裝 php-curl 擴展,不然報錯。
6. 實際上的配置安裝都已完成
在這裏我,進行模板和路由控制器的建立進行一次測試。
建立路由和對應的控制器方法以及修改模板。
路由:Route::get('post/search','Home\PostController@search')->name('user.post.search'); //搜索文章
控制器:
//搜索文章
public function search(Request $request)
{
$this->validate($request,[
'query' => 'required'
]);
$query = $request->input('query');$posts = Post::search($query)->paginate(5); //這裏拿到的是查詢出來的文章,傳遞給模板
return view('home.post.search',compact('posts','query'));
}
模板中:傳遞過去的給模板的主要用到這裏:<p>下面是搜索{{$query}}出現的文章,共{{$posts->total()}}條</p>
total 方法爲 paginate 的計算總數量的方法,其餘直接循環遍歷 posts 經過屬性值拿取便可。