Elasticsearch(如下簡稱es)是一個實時的分佈式搜索和分析引擎。php
在搜索引擎方面,不單單有Elasticsearch,像另外一篇提到的Algolia,還有sphinx、Solr等等,這裏不作評價和比較,本篇主要介紹laravel中如何使用Elasticsearch。html
首選必須安裝有Elasticsearch,請參考 https://www.tech1024.cn/origi... 。laravel
本文基於laravel5.5,其餘版本大同小異。sql
經過composer安裝依賴包數據庫
composer require laravel/scout composer require tamayo/laravel-scout-elastic
在config/app.php文件中的providers數組中加入服務提供者數組
// config/app.php 'providers' => [ // ... Laravel\Scout\ScoutServiceProvider::class, // ... ScoutEngines\Elasticsearch\ElasticsearchProvider::class, ],
使用如下命令生成scout配置文件app
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
在config/scout.php中加入elasticsearch的配置composer
'elasticsearch' => [ 'index' => env('ELASTICSEARCH_INDEX', 'laravel'), 'hosts' => [ env('ELASTICSEARCH_HOST', 'http://localhost:9200'), ], ],
而後咱們打開.env文件,加入scout和elasticsearch的配置elasticsearch
# scout配置 SCOUT_DRIVER=elasticsearch SCOUT_PREFIX= # elasticsearch 配置 ELASTICSEARCH_INDEX=esdemo # elasticsearch 地址 ELASTICSEARCH_HOST=http://172.30.6.1:9200
建立模型app/Student.php,爲方便後續測試,請先建表和填充數據,能夠手動使用sql語句添加數據,也使用laravel自動的數據遷移和填充,能夠參考 https://www.tech1024.cn/origi...分佈式
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Laravel\Scout\Searchable; /** * 學生模型 */ class Student extends Model { use Searchable; /** * 索引名稱 * * @return string */ public function searchableAs() { return 'students_index'; } /** * 可搜索的數據索引 * * @return array */ public function toSearchableArray() { $array = $this->toArray(); // Customize array... return $array; } }
php artisan scout:import "App\Student"
是否是導入成功了呢?
php artisan scout:import "App\Student" Imported [App\Student] models up to ID: 500 Imported [App\Student] models up to ID: 1000 Imported [App\Student] models up to ID: 1500 Imported [App\Student] models up to ID: 2000 Imported [App\Student] models up to ID: 2500 Imported [App\Student] models up to ID: 3000 Imported [App\Student] models up to ID: 3500 Imported [App\Student] models up to ID: 4000 Imported [App\Student] models up to ID: 4500 Imported [App\Student] models up to ID: 5000 Imported [App\Student] models up to ID: 5500 Imported [App\Student] models up to ID: 6000 Imported [App\Student] models up to ID: 6500 Imported [App\Student] models up to ID: 7000 Imported [App\Student] models up to ID: 7500 Imported [App\Student] models up to ID: 8000 Imported [App\Student] models up to ID: 8500 Imported [App\Student] models up to ID: 9000 Imported [App\Student] models up to ID: 9500 Imported [App\Student] models up to ID: 10000 All [App\Student] records have been imported.
咱們訪問es,http://172.30.6.1:9200/esdemo/students_index/_search
是否是已經有了剛剛導入的students_index索引數據
$studens = App\Student::search('成燕')->get(); dd($studens);
能夠填充個百萬條數據試試,檢索速度,是否是比直接查詢數據庫要快不少呢?
更多用法請查閱官方文檔 https://www.elastic.co/guide/...
原文: http://www.tech1024.cn/origin...