Log.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. <?php
  2. namespace common\models\elasticsearch\log;
  3. use yii\behaviors\TimestampBehavior;
  4. use yii\elasticsearch\ActiveRecord;
  5. /**
  6. * Class ElasticSearchCurd
  7. * @package addons\RfExample\common\models
  8. */
  9. class Log extends ActiveRecord
  10. {
  11. public static $currentIndex;
  12. /**
  13. * 数据库名称
  14. * @return string
  15. */
  16. public static function index()
  17. {
  18. return 'es_log';
  19. }
  20. /**
  21. * 表名
  22. *
  23. * @return string
  24. */
  25. public static function type()
  26. {
  27. return 'log';
  28. }
  29. public function attributes()
  30. {
  31. $mapConfig = self::mapConfig();
  32. return array_keys($mapConfig['properties']);
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function rules()
  38. {
  39. return [
  40. [['title'], 'required'],
  41. [['content'], 'required'],
  42. ];
  43. }
  44. public function attributeLabels()
  45. {
  46. return [
  47. 'title' => '标题',
  48. 'content' => '内容',
  49. 'created_at' => '创建时间',
  50. 'updated_at' => '更新时间',
  51. ];
  52. }
  53. /**
  54. * mapping配置(表字段说明)
  55. *
  56. * 如果需要在mapping中添加其他的字段,那么添加后在运行一次updateMapping()
  57. * 另外需要注意的是:elasticSearch的mapping是不能删除的,建了就是建了,如果要删除,您只能删除index(相当于mysql的db)
  58. * 然后重建mapping,因此,您最好写一个脚本,执行es的所有model的mapping。
  59. *
  60. * @return array
  61. */
  62. public static function mapConfig()
  63. {
  64. return [
  65. 'properties' => [
  66. // 不想进行分词等操作,想当成一个和数据库类似的搜索 设置为not_analyzed
  67. // index 默认可不设置
  68. 'title' => ['type' => 'keyword'],
  69. 'content' => ['type' => 'keyword'],
  70. 'created_at' => ['type' => 'long'],
  71. 'updated_at' => ['type' => 'long'],
  72. ],
  73. ];
  74. }
  75. /**
  76. * @return array
  77. */
  78. public static function mapping()
  79. {
  80. return [
  81. static::type() => self::mapConfig(),
  82. ];
  83. }
  84. /**
  85. * 更新字段
  86. *
  87. * @throws \yii\base\InvalidConfigException
  88. */
  89. public static function updateMapping()
  90. {
  91. $db = self::getDb();
  92. $command = $db->createCommand();
  93. if (!$command->indexExists(self::index())) {
  94. $command->createIndex(self::index());
  95. }
  96. $command->setMapping(self::index(), self::type(), self::mapping(),['include_type_name'=>'true']);
  97. }
  98. /**
  99. * @return array
  100. */
  101. public function behaviors()
  102. {
  103. return [
  104. [
  105. 'class' => TimestampBehavior::class,
  106. 'attributes' => [
  107. ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
  108. ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
  109. ],
  110. ],
  111. ];
  112. }
  113. }