在當前互聯網時代,隨著海量數據的爆炸式增長,搜索引擎變得越來越重要。而elasticsearch作為一個高度可擴展的全文搜索引擎,已經逐漸成為開發者們解決搜索問題的首選。
本文將介紹如何在thinkphp6中使用elasticsearch來實現數據檢索和搜索功能,讓我們開始吧。
第一步:安裝elasticsearch-php
使用composer安裝官方提供的elasticsearch-php庫
composer require elasticsearch/elasticsearch
之后我們需要在configelasticsearch.php文件中書寫Elasticsearch連接配置信息,如下:
return [ 'host' => ['your.host.com'], 'port' => 9200, 'scheme' => 'http', 'user' => '', 'pass' => '' ];
注意的是這里沒有密碼,在線上部署時需要添加密碼并使用https方式連接,確保連接是安全的。
第二步:安裝laravel-scout
laravel-scout是Laravel的一個Eloquent ORM全文搜索擴展包,我們需要在thinkphp6中安裝它來實現Elasticsearch的集成,使用下面的命令安裝:
立即學習“PHP免費學習筆記(深入)”;
composer require laravel/scout
第三步:安裝laravel-scout-elastic包
在ThinkPHP6中,我們需要使用擴展包laravel-scout-elastic以實現與Elasticsearch的連接。同樣地,使用下面的命令安裝:
composer require babenkoivan/scout-elasticsearch-driver:^7.0
在app.php中配置scout和elastic driver
return [ 'providers' => [ //... LaravelScoutScoutServiceProvider::class, ScoutElasticsearchElasticsearchServiceProvider::class, //... ], 'aliases' => [ //... 'Elasticsearch' => ScoutElasticsearchFacadesElasticsearch::class, //... ], ];
接著,在configscout.php中配置模型的搜索引擎,如下:
'searchable' => [ AppModelsModel::class => [ 'index' => 'model_index', 'type' => 'model_type' ], ],
以上配置表明我們使用Model::class 模型對象檢索數據,定義Model::class對象對應的索引名稱為model_index ,類型為model_type。
第四步:定義搜索邏輯
我們在Model類中使用Searchable trait并聲明一個public function toSearchableArray()函數,如下:
<?php namespace AppModels; use LaravelScoutSearchable; class Model extends Model { // 使用scout可搜索的trait use Searchable; // 返回可被搜索的模型數據 public function toSearchableArray() { return [ 'title' => $this->title, 'content' => $this->content ]; }
toSearchableArray()函數用于返回可被搜索的數據字段,這里我們例舉了標題和內容兩個字段。
第五步:搜索相關API
最后我們編寫搜索相關的 API,比如搜索結果列表,搜索統計數據等等。這需要我們對 Elasticsearch官方API有一定的了解,具體可以參考Elasticsearch官方文檔。
比如,搜索結果列表 API 的代碼可能如下所示:
use ElasticsearchClientBuilder; class SearchController extends Controller { //搜索結果列表 public function list(Request $request) { $searchQuery = $request->input('q'); //搜索關鍵字 //搜索操作 $elasticsearch = ClientBuilder::create()->setHosts(config('elasticsearch.host'))->build(); $response = $elasticsearch->search([ 'index' => 'model_index', // 索引名稱 'type' => 'model_type', // 類型 'size' => 1000, 'body' => [ 'query' => [ 'bool' => [ 'should' => [ ['match' => ['title' => $request->input('q')]], ['match' => ['content' => $request->input('q')]] ] ] ] ] ]); //格式化返回結果 $result = []; foreach ($response['hits']['hits'] as $hit) { //搜索評分 $hit['_score']; //搜索到的數據 $result[] = $hit['_source']; } return json_encode($result); } }
以上代碼使用了Elasticsearch 官方提供的ElasticsearchClientBuilder類來創建連接,對關鍵字進行查詢,并取回結果列表。你可以將此API中的 $request->input(‘q’) 替換為任何你想要的關鍵字。
文章到此結束,相信你已經可以基本上使用Elasticsearch實現搜索功能了。若您在實踐中遇到問題,請參考官方文檔或提issue以獲得更多幫助。