public function up() { $connection = ActiveRecord::getDb(); if (!($index = Index::index())) { throw new Exception(Index::className() . '::index must be set.'); } $type = Index::type(); if ($connection->createCommand()->indexExists($index)) { $connection->createCommand()->deleteIndex($index); } $connection->createCommand()->createIndex($index, ['mappings' => [$type => ['properties' => ['model_class' => ['type' => 'string', 'index' => 'not_analyzed', 'include_in_all' => false], 'model_id' => ['type' => 'integer', 'include_in_all' => false], 'title' => ['type' => 'string'], 'content' => ['type' => 'string'], 'tags' => ['type' => 'string'], 'updated_at' => ["type" => "date"], 'url_frontend' => ['type' => 'string', 'index' => 'not_analyzed', 'include_in_all' => false], 'url_backend' => ['type' => 'string', 'index' => 'not_analyzed', 'include_in_all' => false]]]]]); echo "Index \"{$index}\" created.\n"; }
/** * @param $class \yii\db\ActiveRecord|string * @return int * @throws \yii\elasticsearch\Exception */ public function upload($class) { $bulk = ''; $index = Index::index(); $type = Index::type(); $timestamp = time(); /** @var \yii\base\Behavior[] */ $behaviors = (new $class())->behaviors; $query = $class::find(); array_walk($behaviors, function ($behavior) use($query) { if ($behavior instanceof TaggableBehavior) { $query->with('tags'); } }); foreach ($query->each() as $model) { /** @var \yii\db\ActiveRecord|\gromver\platform\basic\interfaces\model\SearchableInterface|\gromver\platform\basic\interfaces\model\ViewableInterface $model */ $action = Json::encode(["index" => ["_id" => $model->getPrimaryKey(), "_type" => $type, "_index" => $index]]); $indexModel = Index::findOne(['model_id' => $model->getPrimaryKey(), 'model_class' => $model->className()]) or $indexModel = new Index(); $indexModel->model_id = $model->getPrimaryKey(); $indexModel->model_class = $model->className(); $indexModel->title = $model->getSearchTitle(); $indexModel->content = $model->getSearchContent(); $indexModel->tags = $model->getSearchTags(); $indexModel->url_backend = $model->getBackendViewLink(); $indexModel->url_frontend = $model->getFrontendViewLink(); $indexModel->updated_at = $timestamp; ModuleEvent::trigger(Module::EVENT_BEFORE_CREATE_INDEX . $model->className(), new ElasticIndexEvent(['model' => $model, 'index' => $indexModel, 'sender' => $this->module])); if ($indexModel->validate()) { $bulk .= $action . "\n" . Json::encode($indexModel->toArray()) . "\n"; } } $url = [$index, $type, '_bulk']; $response = ActiveRecord::getDb()->post($url, [], $bulk); $n = 0; $errors = []; foreach ($response['items'] as $item) { if (isset($item['index']['status']) && ($item['index']['status'] == 201 || $item['index']['status'] == 200)) { $n++; } else { $errors[] = $item['index']; } } if (!empty($errors) || isset($response['errors']) && $response['errors']) { throw new Exception(__METHOD__ . ' failed inserting ' . $class . ' model records.', $errors); } return $n; }