CakePHP是一款受歡迎的PHP框架,為開發網路應用程式提供了豐富的功能和工具。 Elasticsearch是另一個流行的工具,用於全文搜尋和分析。在本文中,我們將介紹如何在CakePHP中使用Elasticsearch。
首先,我們需要安裝一個Elasticsearch元件來與CakePHP整合。有許多元件可用,但我們將使用elasticsearch-php元件,它是由Elasticsearch官方提供的PHP客戶端。
使用Composer安裝元件:
composer require elasticsearch/elasticsearch
接下來,我們需要為Elasticsearch設定連線。在config/app.php檔案中,加入以下組態:
'elastic' => [ 'host' => 'localhost',// Elasticsearch主机 'port' => '9200',// Elasticsearch端口 ],
現在,我們需要建立模型來與Elasticsearch進行互動。在src/Model中建立一個名為ElasticsearchModel.php的文件,並編寫以下程式碼:
<?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', ]);// 关联关系 } }
bin/cake elasticsearch create_index ElasticsearchModel
bin/cake elasticsearch:indices create_indexes ElasticsearchModel
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.')); } }
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')); }
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']); }
以上是如何在CakePHP中使用Elasticsearch?的詳細內容。更多資訊請關注PHP中文網其他相關文章!