Home > PHP Framework > Workerman > body text

How to use ElasticSearch for data storage and search in Workerman

王林
Release: 2023-11-07 13:40:50
Original
710 people have browsed it

How to use ElasticSearch for data storage and search in Workerman

In Web development, data storage and search are a very important part. ElasticSearch is an open source distributed search engine that is widely used in data search and analysis. It is capable of handling large amounts of data and provides efficient search and aggregation capabilities. Workerman is a high-performance PHP socket framework suitable for developing applications such as real-time communication, online games, and high-concurrency Web services. In this article, we will introduce how to use ElasticSearch for data storage and search in Workerman.

  1. ElasticSearch installation and configuration

Before we begin, we need to install and configure ElasticSearch. You can download the latest installation package from the official website of ElasticSearch https://www.elastic.co/downloads/elasticsearch and install it according to the operating system type. After the installation is complete, you can start ElasticSearch through the following command:

$ cd elasticsearch/bin
$ ./elasticsearch
Copy after login

At the same time, we can also configure ElasticSearch in the config/elasticsearch.yml file, such as setting the listening port, cluster name, and data storage path.

  1. Installation and configuration of Workerman

Before using Workerman, we need to install and configure it first. Workerman can be installed by entering the following command in the terminal:

$ composer require workerman/workerman
Copy after login

After the installation is complete, we need to create a PHP script file and introduce Workerman's Autoloader class into it, and add the following code to start Workerman:

    require_once __DIR__ . '/vendor/autoload.php';
    use WorkermanWorker;

    $worker = new Worker();
    $worker->count = 4;
    $worker->onWorkerStart = function($worker){
      // do something
    };

    Worker::runAll();
Copy after login

In the above code, we created a Worker object and set the number of processes to 4. At the same time, we also define the behavior when the Worker process starts through the onWorkerStart callback function.

  1. Add, delete, check and modify data in ElasticSearch

When using ElasticSearch for data storage and search in Workerman, we need to master the operations of adding, deleting, checking and modifying data in ElasticSearch, and the specific operations As shown below:

a. Creation of data

In ElasticSearch, the creation of data is done through an HTTP PUT request to the specified index and document type. You can use the following code to create the data :

curl -XPUT http://localhost:9200/{index}/{type}/{id} -d '{
  "title":"ElasticSearch tutorial",
  "tags":["search","elasticsearch"],
  "body":"ElasticSearch is a powerful search engine."
}'
Copy after login

Of course, we can also use PHP code to complete the creation of data:

$client = ElasticsearchClientBuilder::create()->build();
$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'id' => 'my_id',
    'body' => [
        'title' => 'ElasticSearch tutorial',
        'tags' => ['search', 'elasticsearch'],
        'body' => 'ElasticSearch is a powerful search engine.'
    ]
];
$response = $client->index($params);
Copy after login

b. Data query

In ElasticSearch, data query is divided into precise There are two methods: query and fuzzy query. Among them, precise query refers to finding data by specifying fields and values, while fuzzy query refers to finding data through fuzzy matching. You can use the following code to complete the data query:

// 精确查询
$client = ElasticsearchClientBuilder::create()->build();
$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'body' => [
        'query' => [
            'match' => [
                'title' => 'ElasticSearch tutorial'
            ]
        ]
    ]
];
$response = $client->search($params);

// 模糊查询
$client = ElasticsearchClientBuilder::create()->build();
$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'body' => [
        'query' => [
            'wildcard' => [
                'title' => '*search*'
            ]
        ]
    ]
];
$response = $client->search($params);
Copy after login

c. Data update

In ElasticSearch, the data update operation is completed through an HTTP POST request for the specified index and document type. , you can use the following code to update the data:

curl -XPOST http://localhost:9200/{index}/{type}/{id}/_update -d '{
  "doc":{
    "title":"New ElasticSearch tutorial"
  }
}'
Copy after login

Of course, we can also use PHP code to complete the data update:

$client = ElasticsearchClientBuilder::create()->build();
$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'id' => 'my_id',
    'body' => [
        'doc' => [
            'title' => 'New ElasticSearch tutorial'
        ]
    ]
];
$response = $client->update($params);
Copy after login

d. Data deletion

In ElasticSearch , the data deletion operation is completed through an HTTP DELETE request for the specified index and document type. You can use the following code to delete the data:

curl -XDELETE http://localhost:9200/{index}/{type}/{id}
Copy after login

Of course, we can also use PHP code to complete the data deletion:

$client = ElasticsearchClientBuilder::create()->build();
$params = [
    'index' => 'my_index',
    'type' => 'my_type',
    'id' => 'my_id'
];
$response = $client->delete($params);
Copy after login
  1. ElasticSearch example in Workerman

Through the above operations, we have mastered the basic operations of data storage and search in ElasticSearch. Next, we will implement an example of using ElasticSearch for data storage and search in Workerman. The specific code is as follows:

require_once __DIR__ . '/vendor/autoload.php';
use WorkermanWorker;
use ElasticsearchClientBuilder;

// 创建一个Worker对象
$worker = new Worker();
$worker->count = 4;

// 启动一个ElasticSearch客户端
$client = ClientBuilder::create()->build();

// 处理连接请求
$worker->onConnect = function($connection) {
    echo "New connection from " . $connection->getRemoteIp() . PHP_EOL;
};

// 处理数据请求
$worker->onMessage = function($connection, $data) use($client) {
    $params = [
        'index' => 'my_index',
        'type' => 'my_type',
        'body' => [
            'query' => [
                'wildcard' => [
                    'title' => '*' . $data . '*'
                ]
            ]
        ]
    ];

    // 从ElasticSearch检索数据
    $response = $client->search($params);

    // 处理检索结果
    $hits = $response['hits']['hits'];
    if(count($hits) > 0) {
        $result = 'Results:' . PHP_EOL;
        foreach($hits as $hit) {
            $result .= $hit['_source']['title'] . PHP_EOL;
        }
    } else {
        $result = 'No results found.' . PHP_EOL;
    }

    // 发送结果给客户端
    $connection->send($result);
};

Worker::runAll();
Copy after login

In the above code, we first start an ElasticSearch client and create a Worker Object to handle connection and data requests. When a client connects and receives a data request, we retrieve data from ElasticSearch and send the results to the client.

  1. Summary

This article introduces how to use ElasticSearch for data storage and search in Workerman. By mastering the addition, deletion, query, and modification operations of data in ElasticSearch, we can quickly store and search data in web applications. At the same time, we also implemented a simple ElasticSearch application in Workerman to better understand and apply the above operations.

The above is the detailed content of How to use ElasticSearch for data storage and search in Workerman. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!