写在前面Elasticsearch(以下简称es)是一个实时的分布式搜索和分析引擎。搜索引擎方面,不仅有Elasticsearch,还有另一篇文章提到的Algolia,还有sphinx、Solr等,这里不做评价和比较。本文主要介绍如何在laravel中使用Elasticsearch。Elasticsearch必须先安装,请参考https://www.tech1024.com/orig...。本文基于laravel5.5,其他版本类似。准备工作通过composer安装依赖包composerrequirelaravel/scoutcomposerrequiretamayo/laravel-scout-elastic基本配置在config/app.php文件中的providers数组中添加服务提供者//config/app.php'providers'=>[//...Laravel\Scout\ScoutServiceProvider::class,//...ScoutEngines\Elasticsearch\ElasticsearchProvider::class,]使用以下命令生成scout配置文件phpartisanvendor:publish--provider="Laravel\Scout\ScoutServiceProvider"在config/scout.php中添加elasticsearch配置'elasticsearch'=>['index'=>env('ELASTICSEARCH_INDEX','laravel'),'hosts'=>[env('ELASTICSEARCH_HOST','http://localhost:9200'),],],然后我们打开.env文件,添加scout和elasticsearch配置#scout配置SCOUT_DRIVER=elasticsearchSCOUT_PREFIX=#elasticsearch配置ELASTICSEARCH_INDEX=esdemo#elasticsearch地址ELASTICSEARCH_HOST=http://172.30.6.1:9200创建索引,创建模型和fill在数据中创建一个模型app/Student.php。为了后续测试方便,请先建表填写数据。可以手动使用sql语句添加数据,也可以使用laravel自动迁移填充数据。可以参考https://www.tech1024.cn/origi...toArray();//自定义数组...return$array;}}将已有的所有记录导入搜索索引phpartisanscout:import"App\Student"是否导入成功?phpartisanscout:import"App\Student"Imported[App\Student]modelsuptoID:500Imported[App\Student]modelsuptoID:1000Imported[App\Student]modelsuptoID:1500Imported[App\Student]模型uptoID:2000Imported[App\Student]modelsuptoID:2500Imported[App\Student]modelsuptoID:3000Imported[App\Student]modelsuptoID:3500Imported[App\Student]modelsuptoID:4000Imported[App\Student]modelsuptoID:4500Imported[App\Student]mmodelsuptoID:5000Imported[App\Student]modelsuptoID:5500Imported[App\Student]modelsuptoID:6000Imported[App\Student]modelsuptoID:6500Imported[App\Student]modelsuptoID:7000Imported[App\Student]modelsuptoID:7500Imported[App\Student]modelsuptoID:8000Imported[App\Student]modelsuptoID:8500Imported[App\Student]modelsuptoID:9000Imported[App\Student]modelsuptoID:9500Imported[App\Student]modelsuptoID:10000All[App\Student]记录已导入。我们访问es,http://172.30.6.1:9200/esdemo...已经存在了吗?导入的students_index索引数据完整$studens=App\Student::search('Chengyan')->get();dd($studens);你可以试试填一百万条数据,检索速度是不是比直接查询数据库快多少?更多用法请参考官方文档https://www.elastic.co/guide/...原文:http://www.tech1024.com/origi...
