sokolnikov
@sokolnikov

Как правильно работать с elasticsearch в Yii2 через ActiveRecord?

Решил поразбираться с интеграцией elasticsearch в yii2. Использую экстеншн yiisoft/yii2-elasticsearch.

Контроллер:
<?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();
        }
    }
}


Модель:
<?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'];
    }
}


Сначала проверяю, что индекс test с типом country пуст:
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" : [ ]
  }
}


Потом в консоли запускаю ./yii country-index. Все выполняется без ошибок, смотрю опять 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":{}
    } ]
  }
}


Как видно, для типа country появилось пять документов, но без атрибута name и без его содержимого. Почему не создался атрибут и не сохранились его данные? Что я делаю не так?

Да, и можно как-то глобально прописать название используемого индекса для проекта, чтобы не переопределять index() в каждой модели?
  • Вопрос задан
  • 5769 просмотров
Решения вопроса 1
sokolnikov
@sokolnikov Автор вопроса
Всё оказалось просто.
Забыл в модели:

public function rules()
    {
        return [
            ['name', 'required']
        ];
    }
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы