当前位置: 首页 > 后端技术 > PHP

Laravel全文搜索Scout集成Algolia

时间:2023-03-30 05:31:37 PHP

写的比较早你是否担心检索百万数据时的性能和速度?就算你优化了SQL,创建了数据库索引,还是不尽如人意?下面主要介绍laravel如何集成Algolia。Algolia是一家法国初创公司,为您提供毫秒级的实时数据库搜索服务。请记住,它以毫秒为单位。本文基于laravel5.5,其他版本类似。准备工作安装laravel/scout和algolia/algoliasearch-client-phpcomposer需要laravel/scoutcomposer需要algolia/algoliasearch-client-php注册一个algolia账号去https://www.algolia.com/注册一个账号,初学者可以免费使用version,然后在账户的APIKeys菜单中获取ApplicationID和AdminAPIKey。后面会用到基本配置。在config/app.php文件中的providers数组中添加服务提供者//Scout全文搜索Laravel\Scout\ScoutServiceProvider::类,使用如下命令生成scout配置文件phpartisanvendor:publish--provider="Laravel\Scout\ScoutServiceProvider"这个命令会自动生成config/scout.php文件,然后我们打开.env文件,添加scout的配置#scoutConfigureSCOUT_DRIVER=algoliaSCOUT_PREFIX=#algolia'sApplicationIDALGOLIA_APP_ID=xxxxxxxxxxx#algolia'sAdminAPIKeyALGOLIA_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx创建索引创建模型并填写数据创建模型app/Student.php。为了后续测试方便,请创建表格,手动填写数据。使用sql语句添加数据,也使用laravel自动迁移填充数据。可以参考https://www.tech1024.cn/origi...toArray();//自定义数组。..返回$数组;}}将所有现有记录导入搜索索引。phpartisanscout:import"App\Student"可能报如下错误[AlgoliaSearch\AlgoliaConnectionException]Hostsunreachable:Resolvingtimedoutafter1000毫秒,Resolvingtimedoutafter1000毫秒,Resolvingtimedoutafter3000毫秒,Resolvingtimeedoutafter3000毫秒这是因为默认algoliasearch-client配置的连接超时时间是1秒,由于网速,我们可以修改连接时间来创建一个app/Services/Scout/EngineManager.php文件如下setConnectTimeout(30,30,30);返回新的AlgoliaEngine($algolia);}}打开app/Providers/AppServiceProvider.php,在boot()中添加如下代码publicfunctionboot(){//...省略前面的代码$this->app->singleton(\Laravel\Scout\EngineManager::class,function($app){returnnew\App\Services\Scout\EngineManager($app);});}导入成功了吗?phpartisanscout:import"App\Student"Imported[App\Student]modelsuptoID:500Imported[App\Student]modelsuptoID:1000Imported[App\Student]modelsuptoID:1500Imported[App\Student]模型uptoID:2000Imported[App\Student]模型uptoID:2500Imported[App\Student]modelsuptoID:3000Imported[App\Student]modelsuptoID:3500Imported[App\Student]modelsuptoID:4000Imported[App\Student]modelsuptoID:4500Imported[App\Student]modelsuptoID: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]模型]]型号最多ID:10000所有[App\Student]记录已导入。https://www.algolia.com账号后...刚才导入的students_index索引数据的菜单已经可以了$studens=App\Student::search('程妍')->get();dd($学生);你可以尝试填写几百万条数据。检索速度是不是比直接查询数据库快很多?更多用法请参考官方文档https://www.algolia.com/doc/a...不过作者不推荐使用algolia搜索引擎。毕竟国内网速太慢,以后笔者会戒掉laravel、elasticsearch、sphinx。相关资讯,请继续关注原文https://www.tech1024.cn/origi...

猜你喜欢