search
HomePHP FrameworkWorkermanHow 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
workermanelasticsearchsearchdata 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

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

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

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."
}'

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

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

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"
  }
}'

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

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}

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

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
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
What Are the Key Features of Workerman's Built-in WebSocket Client?What Are the Key Features of Workerman's Built-in WebSocket Client?Mar 18, 2025 pm 04:20 PM

Workerman's WebSocket client enhances real-time communication with features like asynchronous communication, high performance, scalability, and security, easily integrating with existing systems.

How to Use Workerman for Building Real-Time Collaboration Tools?How to Use Workerman for Building Real-Time Collaboration Tools?Mar 18, 2025 pm 04:15 PM

The article discusses using Workerman, a high-performance PHP server, to build real-time collaboration tools. It covers installation, server setup, real-time feature implementation, and integration with existing systems, emphasizing Workerman's key f

What Are the Best Ways to Optimize Workerman for Low-Latency Applications?What Are the Best Ways to Optimize Workerman for Low-Latency Applications?Mar 18, 2025 pm 04:14 PM

The article discusses optimizing Workerman for low-latency applications, focusing on asynchronous programming, network configuration, resource management, data transfer minimization, load balancing, and regular updates.

How to Implement Real-Time Data Synchronization with Workerman and MySQL?How to Implement Real-Time Data Synchronization with Workerman and MySQL?Mar 18, 2025 pm 04:13 PM

The article discusses implementing real-time data synchronization using Workerman and MySQL, focusing on setup, best practices, ensuring data consistency, and addressing common challenges.

What Are the Key Considerations for Using Workerman in a Serverless Architecture?What Are the Key Considerations for Using Workerman in a Serverless Architecture?Mar 18, 2025 pm 04:12 PM

The article discusses integrating Workerman into serverless architectures, focusing on scalability, statelessness, cold starts, resource management, and integration complexity. Workerman enhances performance through high concurrency, reduced cold sta

How to Build a High-Performance E-Commerce Platform with Workerman?How to Build a High-Performance E-Commerce Platform with Workerman?Mar 18, 2025 pm 04:11 PM

The article discusses building a high-performance e-commerce platform using Workerman, focusing on its features like WebSocket support and scalability to enhance real-time interactions and efficiency.

What Are the Advanced Features of Workerman's WebSocket Server?What Are the Advanced Features of Workerman's WebSocket Server?Mar 18, 2025 pm 04:08 PM

Workerman's WebSocket server enhances real-time communication with features like scalability, low latency, and security measures against common threats.

How to Use Workerman for Building Real-Time Analytics Dashboards?How to Use Workerman for Building Real-Time Analytics Dashboards?Mar 18, 2025 pm 04:07 PM

The article discusses using Workerman, a high-performance PHP server, to build real-time analytics dashboards. It covers installation, server setup, data processing, and frontend integration with frameworks like React, Vue.js, and Angular. Key featur

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool