国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home PHP Framework ThinkPHP How to perform Elasticsearch full-text search operation in ThinkPHP6?

How to perform Elasticsearch full-text search operation in ThinkPHP6?

Jun 12, 2023 am 10:38 AM
thinkphp elasticsearch research all

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');

    // 創(chuàng)建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;
}

/**
 * 創(chuàng)建索引
 *
 * @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('創(chuàng)建索引失?。? . $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 文檔數(shù)據(jù)
 * @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是一款優(yōu)秀的PHP開發(fā)框架'
    ]);
    $this->elasticsearchService->indexDocument('articles', '2', [
        'title' => 'Laravel',
        'content' => 'Laravel是一款流行的PHP開發(fā)框架'
    ]);
    $this->elasticsearchService->indexDocument('articles', '3', [
        'title' => 'Symfony',
        'content' => 'Symfony是一款PHP開發(fā)框架'
    ]);

    // 搜索框
    $search = Request::instance()->get('search', '');

    // 搜索結(jié)果
    $results = $this->elasticsearchService->searchDocuments('articles', $search);

    // 返回搜索結(jié)果
    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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

Development suggestions: How to use the ThinkPHP framework for API development Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

See all articles