ThinkPHP6中如何進行Elasticsearch全文搜索操作?

隨著互聯網的快速發展和數據量的增加,如何高效地進行全文搜索已經成為了越來越多開發者面臨的問題。elasticsearch是一種流行的全文搜索引擎,它能夠快速處理大量的文本數據,并對其進行檢索和分析,這使得它成為了很多web應用程序的首選工具。現在,thinkphp6也已經開始支持elasticsearch全文搜索操作,為開發者帶來更加高效的搜索方案。

首先,我們需要在thinkphp6中安裝Elasticsearch支持庫,這可以通過在composer.json文件中添加以下代碼來完成:

“require”: {

"elasticsearch/elasticsearch": "^7.0"

}

然后在項目根目錄下執行composer update命令,即可完成Elasticsearch支持庫的安裝。

立即學習PHP免費學習筆記(深入)”;

接下來,我們將創建一個Elasticsearch服務提供者,將Elasticsearch客戶端實例綁定到容器中,以便我們隨時可以通過依賴注入在應用程序中使用它。在App/Provider目錄下,創建ElasticsearchServiceProvider.php文件,代碼如下:

namespace appprovider;

use ElasticsearchClientBuilder;
use thinkService;

class ElasticsearchServiceProvider extends Service
{

public function register() {     // 獲取config/elasticsearch.php配置     $config = $this->app->config->get('elasticsearch');      // 創建Elasticsearch客戶端實例     $client = ClientBuilder::create()->setHosts($config['hosts'])->build();      // 將Elasticsearch客戶端實例綁定到容器中     $this->app->bind('elasticsearch', $client); }

}

在本例中,我們首先從config/elasticsearch.php配置文件中獲取Elasticsearch的主機地址,然后使用ClientBuilder類創建一個Elasticsearch客戶端實例,并將其綁定到應用程序的容器中,這樣我們就可以隨時使用它來執行全文搜索操作了。

接下來,我們將演示如何在ThinkPHP6應用程序中進行全文搜索操作。在這里,我們創建一個ElasticsearchService服務類,該類包含了幾個簡單的方法來執行搜索操作。代碼如下:

namespace appservice;

use ElasticsearchClient;
use ElasticsearchCommonExceptionsMissing404Exception;
use Throwable;

class ElasticsearchService
{

protected $client;  public function __construct(Client $client) {     $this->client = $client; }  /**  * 創建索引  *  * @param string $indexName 索引名稱  * @return bool  */ public function createIndex(string $indexName) {     $params = [         'index' => $indexName,         'body' => [             'mappings' => [                 'properties' => [                     'title' => [                         'type' => 'text'                     ],                     'content' => [                         'type' => 'text'                     ]                 ]             ]         ]     ];      try {         $response = $this->client->indices()->create($params);         return true;     } catch (Throwable $e) {         throw new Exception('創建索引失敗:' . $e->getMessage());     } }  /**  * 刪除索引  *  * @param string $indexName 索引名稱  * @return bool  */ public function deleteIndex(string $indexName) {     try {         $response = $this->client->indices()->delete(['index' => $indexName]);         return true;     } catch (Missing404Exception $e) {         return false;     } catch (Throwable $e) {         throw new Exception('刪除索引失敗:' . $e->getMessage());     } }  /**  * 添加文檔  *  * @param string $indexName 索引名稱  * @param string $id 文檔ID  * @param array $data 文檔數據  * @return bool  */ public function indexDocument(string $indexName, string $id, array $data) {     $params = [         'index' => $indexName,         'id' => $id,         'body' => $data     ];      try {         $response = $this->client->index($params);         return true;     } catch (Throwable $e) {         throw new Exception('添加文檔失敗:' . $e->getMessage());     } }  /**  * 搜索文檔  *  * @param string $indexName 索引名稱  * @param string $query 查詢字符串  * @return array  */ public function searchDocuments(string $indexName, string $query) {     $params = [         'index' => $indexName,         'body' => [             'query' => [                 'match' => [                     '_all' => $query                 ]             ]         ]     ];      try {         $response = $this->client->search($params);         return $response['hits']['hits'];     } catch (Throwable $e) {         throw new Exception('搜索文檔失敗:' . $e->getMessage());     } }

}

在此服務類中,我們定義了四個方法:createIndex、deleteIndex、indexDocument和searchDocuments。這些方法封裝了Elasticsearch API的調用,可以輕松地創建、刪除索引,添加和搜索文檔。

現在我們將演示如何使用這些方法。在這里,我們將創建一個測試頁面,可以創建一個名為“articles”的索引,并添加一些文檔,然后使用搜索框搜索文檔。在App/controller目錄下,創建一個ElasticsearchTestController.php文件,代碼如下:

namespace appcontroller;

use appServiceElasticsearchService;
use thinkRequest;

class ElasticsearchTestController extends BaseController
{

protected $elasticsearchService;  public function __construct(ElasticsearchService $elasticsearchService) {     $this->elasticsearchService = $elasticsearchService; }  public function index() {     $this->elasticsearchService->createIndex('articles');      // 添加測試文檔     $this->elasticsearchService->indexDocument('articles', '1', [         'title' => 'ThinkPHP',         'content' => 'ThinkPHP是一款優秀的PHP開發框架'     ]);     $this->elasticsearchService->indexDocument('articles', '2', [         'title' => 'Laravel',         'content' => 'Laravel是一款流行的PHP開發框架'     ]);     $this->elasticsearchService->indexDocument('articles', '3', [         'title' => 'Symfony',         'content' => 'Symfony是一款PHP開發框架'     ]);      // 搜索框     $search = Request::instance()->get('search', '');      // 搜索結果     $results = $this->elasticsearchService->searchDocuments('articles', $search);      // 返回搜索結果     return $this->fetch('index', [         'results' => $results     ]); }

}

在此控制器中,我們注入了ElasticsearchService服務,并在index方法中調用了createIndex、indexDocument和searchDocuments方法來創建索引、添加文檔和執行搜索操作。搜索框和搜索結果也被包含在了index方法中。

至此,我們已經完成了在ThinkPHP6應用程序中使用Elasticsearch進行全文搜索操作的演示。值得注意的是,本例僅僅是一個簡單的演示用例,實際項目中需要更加細致地進行索引設計和文檔管理,以確保搜索效率和搜索結果的準確性。

總的來說,隨著Elasticsearch的廣泛應用,它已經成為了Web應用程序中一種非常流行和高效的全文搜索引擎。在ThinkPHP6中,通過使用Elasticsearch支持庫和Elasticsearch API,我們可以輕松地進行全文搜索操作。

? 版權聲明
THE END
喜歡就支持一下吧
點贊8 分享