程序员

在Yii2中使用Elasticsearch方法

2016-07-30  本文已影响0人  Kerwin丶

一、修改config/web.php文件,引入Elasticsearch配置####

'components' => [
...
    'elasticsearch' => [
                'class' => 'yii\elasticsearch\Connection',
                'nodes' => [
                        ['http_address' => '127.0.0.1:9200']
                ],
                'autodetectCluster' => false
            ],
...
]

二、创建数据####

1、建立model

<?php
namespace app\models;

use yii\elasticsearch\ActiveRecord;

class Es extends ActiveRecord
{
    
    public function attributes(){
        return ['id', 'name', 'sex', 'age', 'create_time'];
    }
}
?>

2、建立controller

<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\Es;

/**
* 
*/
class EsController extends Controller
{
    
    public function actionIndex(){
        $Es = new Es();
        $Es->primaryKey = 1;//primaryKey 定义 _id 

        $name = 'John';
        $sex = '男';
        $age = '19';

        $Es->name = $name;
        $Es->sex = $sex;
        $Es->age = $age;
        $Es->create_time = time();
        $Es->save();
    }
}
?>

三、查询Es数据###

查询所有数据

    public function actionIndex(){
        $Es = new Es();
        $res = $Es::find()->all();
        
        var_dump($res);
    }

得到的是对象

object(app\models\Es)#66 (12) {
  ["_id":"yii\elasticsearch\ActiveRecord":private]=>
  string(1) "1"
  ["_score":"yii\elasticsearch\ActiveRecord":private]=>
  NULL
  ["_version":"yii\elasticsearch\ActiveRecord":private]=>
  int(1)
  ["_highlight":"yii\elasticsearch\ActiveRecord":private]=>
  NULL
  ["_attributes":"yii\db\BaseActiveRecord":private]=>
  array(4) {
    ["name"]=>
    string(4) "John"
    ["sex"]=>
    string(3) "男"
    ["age"]=>
    string(2) "19"
    ["create_time"]=>
    int(1469073295)
  }
  ["_oldAttributes":"yii\db\BaseActiveRecord":private]=>
  array(4) {
    ["name"]=>
    string(4) "John"
    ["sex"]=>
    string(3) "男"
    ["age"]=>
    string(2) "19"
    ["create_time"]=>
    int(1469073295)
  }
  ["_related":"yii\db\BaseActiveRecord":private]=>
  array(0) {
  }
  ["_errors":"yii\base\Model":private]=>
  NULL
  ["_validators":"yii\base\Model":private]=>
  NULL
  ["_scenario":"yii\base\Model":private]=>
  string(7) "default"
  ["_events":"yii\base\Component":private]=>
  array(0) {
  }
  ["_behaviors":"yii\base\Component":private]=>
  array(0) {
  }
}
上一篇 下一篇

猜你喜欢

热点阅读