Home > Backend Development > PHP Tutorial > How to use Elasticsearch with CakePHP?

How to use Elasticsearch with CakePHP?

PHPz
Release: 2023-06-03 21:34:01
Original
1056 people have browsed it

CakePHP is a popular PHP framework that provides rich features and tools for developing web applications. Elasticsearch is another popular tool used for full-text search and analysis. In this article, we will introduce how to use Elasticsearch with CakePHP.

  1. Install the Elasticsearch component

First, we need to install an Elasticsearch component to integrate with CakePHP. There are many components available, but we will use the elasticsearch-php component, which is the PHP client officially provided by Elasticsearch.

Install the component using Composer:

composer require elasticsearch/elasticsearch
Copy after login
  1. Configure the connection

Next, we need to configure the connection for Elasticsearch. In the config/app.php file, add the following configuration:

'elastic' => [
    'host' => 'localhost',// Elasticsearch主机
    'port' => '9200',// Elasticsearch端口
],
Copy after login
  1. Create model

Now, we need to create the model to interact with Elasticsearch. Create a file called ElasticsearchModel.php in src/Model and write the following code:

<?php
namespace AppModel;

use CakeElasticSearchIndex;

class ElasticsearchModel extends Index
{
    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setIndex('my_index');// Elasticsearch索引名称
        $this->setType('my_type');// Elasticsearch类型名称
        
        $this->primaryKey('id');// 主键
        $$this->belongsTo('Parent', [
            'className' => 'Parent',
            'foreignKey' => 'parent_id',
        ]);// 关联关系
    }
}
Copy after login
  1. Create index

Now we can create the Elasticsearch index. Before version 4.x, use the following command:

bin/cake elasticsearch create_index ElasticsearchModel
Copy after login

After version 4.x, use the following command:

bin/cake elasticsearch:indices create_indexes ElasticsearchModel
Copy after login
  1. Add documentation

Next, we can add documentation. In the controller, we can write the following code:

public function add()
{
    $this->request->allowMethod('post');
    $data = $this->request->data;

    $document = $this->ElasticsearchModel->newDocument();
    $document->id = $data['id'];
    $document->parent_id = $data['parent_id'];
    $document->title = $data['title'];
    $document->content = $data['content'];
    $document->body = $data['body'];

    if ($this->ElasticsearchModel->save($document)) {
        $this->Flash->success(__('The document has been saved.'));
        return $this->redirect(['action' => 'index']);
    } else {
        $this->Flash->error(__('The document could not be saved. Please, try again.'));
    }
}
Copy after login
  1. Search Documents

Now we can search documents. In the controller, we can write the following code:

public function search()
{
    $this->paginate = [
        'contain' => ['Parent'],
    ];

    $query = $this->request->getQuery('q');
    $documents = $this->ElasticsearchModel->find()
        ->contain(['Parent'])
        ->where(['title LIKE' => "%$query%"])
        ->paginate();

    $this->set(compact('documents'));
}
Copy after login

We can use Paginator in the View to display the search results.

  1. Delete Document

If we need to delete the document, we can use the following code:

public function delete($id)
{
    $this->request->allowMethod(['post', 'delete']);
    $document = $this->ElasticsearchModel->find()->where(['id' => $id])->firstOrFail();
    if ($this->ElasticsearchModel->delete($document)) {
        $this->Flash->success(__('The document has been deleted.'));
    } else {
        $this->Flash->error(__('The document could not be deleted. Please, try again.'));
    }

    return $this->redirect(['action' => 'index']);
}
Copy after login

Conclusion

The above is in CakePHP Method using Elasticsearch. In this process, we used the elasticsearch-php component to connect to Elasticsearch, create an Elasticsearch model, create an index, add documents, search documents and delete documents.

For developers, using Elasticsearch is a simple and effective way to implement full-text search and analysis. Using Elasticsearch in CakePHP can help us build web applications more efficiently and provide better user experience and performance.

The above is the detailed content of How to use Elasticsearch with CakePHP?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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