Home PHP Framework Workerman How to use ElasticSearch for data storage and search in Workerman

How to use ElasticSearch for data storage and search in Workerman

Nov 07, 2023 pm 01:40 PM
workerman elasticsearch search data storage

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!

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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to search for users in Xianyu How to search for users in Xianyu Feb 24, 2024 am 11:25 AM

How does Xianyu search for users? In the software Xianyu, we can directly find the users we want to communicate with in the software. But I don’t know how to search for users. Just view it among the users after searching. Next is the introduction that the editor brings to users about how to search for users. If you are interested, come and take a look! How to search for users in Xianyu? Answer: View details among the searched users. Introduction: 1. Enter the software and click on the search box. 2. Enter the user name and click Search. 3. Select [User] under the search box to find the corresponding user.

How to use Baidu advanced search How to use Baidu advanced search Feb 22, 2024 am 11:09 AM

How to use Baidu Advanced Search Baidu search engine is currently one of the most commonly used search engines in China. It provides a wealth of search functions, one of which is advanced search. Advanced search can help users search for the information they need more accurately and improve search efficiency. So, how to use Baidu advanced search? The first step is to open the Baidu search engine homepage. First, we need to open Baidu’s official website, which is www.baidu.com. This is the entrance to Baidu search. In the second step, click the Advanced Search button. On the right side of the Baidu search box, there is

Implement file upload and download in Workerman documents Implement file upload and download in Workerman documents Nov 08, 2023 pm 06:02 PM

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

Why can't localstorage successfully save data? Why can't localstorage successfully save data? Jan 03, 2024 pm 01:41 PM

Why does storing data to localstorage always fail? Need specific code examples In front-end development, we often need to store data on the browser side to improve user experience and facilitate subsequent data access. Localstorage is a technology provided by HTML5 for client-side data storage. It provides a simple way to store data and maintain data persistence after the page is refreshed or closed. However, when we use localstorage for data storage, sometimes

WPS table cannot find the data you are searching for, please check the search option location WPS table cannot find the data you are searching for, please check the search option location Mar 19, 2024 pm 10:13 PM

In the era dominated by intelligence, office software has also become popular, and Wps forms are adopted by the majority of office workers due to their flexibility. At work, we are required not only to learn simple form making and text entry, but also to master more operational skills in order to complete the tasks in actual work. Reports with data and using forms are more convenient, clear and accurate. The lesson we bring to you today is: The WPS table cannot find the data you are searching for. Why please check the search option location? 1. First select the Excel table and double-click to open it. Then in this interface, select all cells. 2. Then in this interface, click the "Edit" option in "File" in the top toolbar. 3. Secondly, in this interface, click "

How to search for stores on mobile Taobao How to search for store names How to search for stores on mobile Taobao How to search for store names Mar 13, 2024 am 11:00 AM

The mobile Taobao app software provides a lot of good products. You can buy them anytime and anywhere, and everything is genuine. The price tag of each product is clear. There are no complicated operations at all, making you enjoy more convenient shopping. . You can search and purchase freely as you like. The product sections of different categories are all open. Add your personal delivery address and contact number to facilitate the courier company to contact you, and check the latest logistics trends in real time. Then some new users are using it for the first time. If you don’t know how to search for products, of course you only need to enter keywords in the search bar to find all the product results. You can’t stop shopping freely. Now the editor will provide detailed online methods for mobile Taobao users to search for store names. 1. First open the Taobao app on your mobile phone,

Which one is better, swoole or workerman? Which one is better, swoole or workerman? Apr 09, 2024 pm 07:00 PM

Swoole and Workerman are both high-performance PHP server frameworks. Known for its asynchronous processing, excellent performance, and scalability, Swoole is suitable for projects that need to handle a large number of concurrent requests and high throughput. Workerman offers the flexibility of both asynchronous and synchronous modes, with an intuitive API that is better suited for ease of use and projects that handle lower concurrency volumes.

How to implement the basic usage of Workerman documents How to implement the basic usage of Workerman documents Nov 08, 2023 am 11:46 AM

Introduction to how to implement the basic usage of Workerman documents: Workerman is a high-performance PHP development framework that can help developers easily build high-concurrency network applications. This article will introduce the basic usage of Workerman, including installation and configuration, creating services and listening ports, handling client requests, etc. And give corresponding code examples. 1. Install and configure Workerman. Enter the following command on the command line to install Workerman: c

See all articles