Home >PHP Framework >ThinkPHP >How to perform Elasticsearch full-text search operation in ThinkPHP6?
With the rapid development of the Internet and the increase in data volume, how to efficiently perform full-text search has become a problem faced by more and more developers. Elasticsearch is a popular full-text search engine that can quickly process large amounts of text data, retrieve and analyze it, making it the tool of choice for many web applications. Now, ThinkPHP6 has also begun to support Elasticsearch full-text search operations, bringing developers a more efficient search solution.
First, we need to install the Elasticsearch support library in ThinkPHP6, which can be done by adding the following code in the composer.json file:
"require": {
"elasticsearch/elasticsearch": "^7.0"
}
Then execute the composer update command in the project root directory to complete the installation of the Elasticsearch support library.
Next, we will create an Elasticsearch service provider and bind the Elasticsearch client instance into the container so that we can use it in our application at any time through dependency injection. In the App/Provider directory, create the ElasticsearchServiceProvider.php file with the following code:
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); }
}
In this example, we first get the host address of Elasticsearch from the config/elasticsearch.php configuration file, and then use the ClientBuilder class to create an Elasticsearch client instance , and bind it to the application's container so that we can use it to perform full-text search operations at any time.
Next, we will demonstrate how to perform full-text search operations in ThinkPHP6 applications. Here, we create an ElasticsearchService service class, which contains several simple methods to perform search operations. The code is as follows:
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()); } }
}
In this service class, we define four methods: createIndex, deleteIndex, indexDocument and searchDocuments. These methods encapsulate calls to the Elasticsearch API, making it easy to create and delete indexes, add and search documents.
Now we will demonstrate how to use these methods. Here we will create a test page, create an index called "articles", add some documents, and then use the search box to search for the documents. In the App/controller directory, create an ElasticsearchTestController.php file with the following code:
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 ]); }
}
In this controller, we injected the ElasticsearchService service and called the createIndex, indexDocument and searchDocuments methods in the index method to create the index and add documents and perform search operations. The search box and search results are also included in the index method.
So far, we have completed the demonstration of using Elasticsearch for full-text search operations in ThinkPHP6 applications. It is worth noting that this example is just a simple demonstration use case. In actual projects, more detailed index design and document management are required to ensure search efficiency and accuracy of search results.
In general, with the widespread application of Elasticsearch, it has become a very popular and efficient full-text search engine in web applications. In ThinkPHP6, by using the Elasticsearch support library and Elasticsearch API, we can easily perform full-text search operations.
The above is the detailed content of How to perform Elasticsearch full-text search operation in ThinkPHP6?. For more information, please follow other related articles on the PHP Chinese website!