Cài đặt bằng composer elastic Search với dòng vào file composer.json
"yiisoft/yii2-elasticsearch": "~2.1-dev"
Vì mình dùng elasticsearch bản 6.3 nên dùng lệnh trên nếu bạn dùng bản thập hơn thì để 2.0.0 nhé
Tiếp theo bạn thêm file common\config\main-local.php phần components
'elasticsearch' => [ 'class' => 'yii\elasticsearch\Connection', 'nodes' => [ ['http_address' => '168.235.xxx.xxx:9200'], // configure more hosts if you have a cluster ], ],
Tạo file common\models\Elastic.php
<?php namespace common\models; use yii\elasticsearch\ActiveRecord; class Elastic extends ActiveRecord { public function attributes() { return ['content','slug','title']; } }
File controller :
<?php namespace frontend\controllers; use yii\base\Controller; use common\models\Elastic; class ElasticController extends Controller { public function actionIndex() { $elastic = new Elastic(); $elastic->title ='test 2'; $elastic->content ='Đây là content của test elastic'; if ($elastic->insert()) { echo 'add thành công'; } else { echo 'add thất bại'; } } public function actionFind() { $elastic = new Elastic(); $data = $elastic->findAll(['title'=>'test']); foreach ($data as $key => $value) { echo $value->title; } } }