S
S
sokolnikov2015-09-08 20:22:08
Yii
sokolnikov, 2015-09-08 20:22:08

How to properly work with elasticsearch in Yii2 through ActiveRecord?

I decided to deal with the integration of elasticsearch in yii2. I am using yiisoft/yii2-elasticsearch extension.
Controller:

<?php
namespace console\controllers;

use Yii;
use console\models\CountryElastic;

class CountryIndexController extends \yii\console\Controller
{
    public function actionIndex()
    {
        for ($i=0; $i<5; $i++) {
            $countryElastic = new CountryElastic();
            $countryElastic->attributes = ['name' => 'country name' . $i];
            $countryElastic->save();
        }
    }
}

Model:
<?php
namespace console\models;

use Yii;

class CountryElastic extends \yii\elasticsearch\ActiveRecord
{
    public static function index() {
        return 'test';
    }

    public static function type() {
        return 'country';
    }

    public function attributes()
    {
        return ['name'];
    }
}

First I check that the test index with country type is empty:
127.0.0.1:9200/test/country/_search?pretty=true
{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 0,
    "max_score" : null,
    "hits" : [ ]
  }
}

Then in the console I run ./yii country-index. Everything runs without errors, I look again at 127.0.0.1:9200/test/country/_search?pretty=true
{
  "took" : 4,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 5,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "test",
      "_type" : "country",
      "_id" : "AU-ts-L5LdBGMLEkdKiZ",
      "_score" : 1.0,
      "_source":{}
    }, {
      "_index" : "test",
      "_type" : "country",
      "_id" : "AU-ts-M6LdBGMLEkdKib",
      "_score" : 1.0,
      "_source":{}
    }, {
      "_index" : "test",
      "_type" : "country",
      "_id" : "AU-ts-NCLdBGMLEkdKid",
      "_score" : 1.0,
      "_source":{}
    }, {
      "_index" : "test",
      "_type" : "country",
      "_id" : "AU-ts-M-LdBGMLEkdKic",
      "_score" : 1.0,
      "_source":{}
    }, {
      "_index" : "test",
      "_type" : "country",
      "_id" : "AU-ts-M0LdBGMLEkdKia",
      "_score" : 1.0,
      "_source":{}
    } ]
  }
}

As you can see, five documents appeared for the country type, but without the name attribute and without its content. Why was the attribute not created and its data not saved? What am I doing wrong?
Yes, and is it possible to somehow globally prescribe the name of the index used for the project, so as not to override index() in each model?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question