| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- <?php
- namespace common\models\elasticsearch\log;
- use yii\behaviors\TimestampBehavior;
- use yii\elasticsearch\ActiveRecord;
- /**
- * Class ElasticSearchCurd
- * @package addons\RfExample\common\models
- */
- class Log extends ActiveRecord
- {
- public static $currentIndex;
- /**
- * 数据库名称
- * @return string
- */
- public static function index()
- {
- return 'es_log';
- }
- /**
- * 表名
- *
- * @return string
- */
- public static function type()
- {
- return 'log';
- }
- public function attributes()
- {
- $mapConfig = self::mapConfig();
- return array_keys($mapConfig['properties']);
- }
- /**
- * {@inheritdoc}
- */
- public function rules()
- {
- return [
- [['title'], 'required'],
- [['content'], 'required'],
- ];
- }
- public function attributeLabels()
- {
- return [
- 'title' => '标题',
- 'content' => '内容',
- 'created_at' => '创建时间',
- 'updated_at' => '更新时间',
- ];
- }
- /**
- * mapping配置(表字段说明)
- *
- * 如果需要在mapping中添加其他的字段,那么添加后在运行一次updateMapping()
- * 另外需要注意的是:elasticSearch的mapping是不能删除的,建了就是建了,如果要删除,您只能删除index(相当于mysql的db)
- * 然后重建mapping,因此,您最好写一个脚本,执行es的所有model的mapping。
- *
- * @return array
- */
- public static function mapConfig()
- {
- return [
- 'properties' => [
- // 不想进行分词等操作,想当成一个和数据库类似的搜索 设置为not_analyzed
- // index 默认可不设置
- 'title' => ['type' => 'keyword'],
- 'content' => ['type' => 'keyword'],
- 'created_at' => ['type' => 'long'],
- 'updated_at' => ['type' => 'long'],
- ],
- ];
- }
- /**
- * @return array
- */
- public static function mapping()
- {
- return [
- static::type() => self::mapConfig(),
- ];
- }
- /**
- * 更新字段
- *
- * @throws \yii\base\InvalidConfigException
- */
- public static function updateMapping()
- {
- $db = self::getDb();
- $command = $db->createCommand();
- if (!$command->indexExists(self::index())) {
- $command->createIndex(self::index());
- }
- $command->setMapping(self::index(), self::type(), self::mapping(),['include_type_name'=>'true']);
- }
- /**
- * @return array
- */
- public function behaviors()
- {
- return [
- [
- 'class' => TimestampBehavior::class,
- 'attributes' => [
- ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
- ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
- ],
- ],
- ];
- }
- }
|