Yii2 Elasticsearch 操作Demo

此处用的是yii2 高级版

1: 配置 : common/config/main.php

    'components' => [
        'elasticsearch' => [
            'class' => 'yii\elasticsearch\Connection',
            'nodes' => [
                ['http_address' => '192.168.101.5:9200'],
                // configure more hosts if you have a cluster
            ],
            'dslVersion' => 7, // default is 5
            'autodetectCluster' => false
        ],

    ],

2: 类封装

<?php
/**
 *  
 * @file ConsultingService.php
 * @author 
 * @version 1.0
 * @date 2021-07-15
 */

namespace common\tools\es;

use frontend\models\ConsultingService;
use frontend\models\QuestionAsk;
use yii\elasticsearch\ActiveRecord;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;


class ConsultingService extends ActiveRecord
{
    /**
     * 数据库
     */
    public static function getDb()
    {
        return \Yii::$app->get('elasticsearch');
    }

    /**
     * 索引
     */
    public static function index()
    {
        return 'consulting_service';
    }

    /**
     * 设置索引别名
     */
    public static function alias()
    {
        return 'consulting_service_new';
    }

    /**
     * 类型
     */
    public static function type()
    {
        return '_doc';
    }

    /**
     * 返回字段
     */
    public function attributes()
    {
        $mapConfig = self::mapConfig();
        return array_keys($mapConfig['properties']);
    }

    /**
     * 映射配置
     */
    public static function mapConfig()
    {
        return [
            'properties' => [
                'id' => ['type' => 'integer'],  //问题的id
                'department_category_id' => ['type' => 'integer'], //科室分类的id
                'title' => ['type' => 'text', 'analyzer' => "ik_max_word"], //咨询的问题标题
                'description' => ['type' => 'text', 'analyzer' => "ik_max_word"], //问题描述
            ]
        ];
    }

    /**
     * 设置映射
     */
    public static function mapping()
    {
        return self::mapConfig();
    }

    /**
     * 获取映射
     */
    public static function getMapping()
    {
        $db = self::getDb();
        $command = $db->createCommand();
        return $command->getMapping(static::index());
    }

    /**
     * 更新映射
     */
    public static function updateMapping()
    {
        $db = self::getDb();
        $command = $db->createCommand();
        if (!$command->indexExists(self::index() . '_' . date('d'))) {
            return $command->createIndex(self::index() . '_' . date('d'), [
                'mappings' => static::mapping(),
            ]);
        } else {
            return $command->setMapping(self::index() . '_' . date('d'), '', self::mapping());
        }
    }

    /**
     * 更新别名指向
     */
    public static function updateAlias()
    {
        $db = self::getDb();
        $command = $db->createCommand();
        $alias = $command->getAliasInfo();
        $currentIndex = key($alias);

        $result = $command->addAlias(self::index() . '_' . date('d'), self::alias());
        if ($currentIndex) {
            $result = $command->removeAlias($currentIndex, self::alias());
        }
        return $result;
    }

    /**
     * 创建索引
     */
    public static function createIndex()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $result = $command->createIndex(static::index(), [
            'mappings' => static::mapping(),
        ]);

        return $result;
    }

    /**
     * 删除索引
     */
    public static function deleteIndex()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $result = $command->deleteIndex(static::index());
        return $result;
    }

    /**
     * 获取医院详情
     */
    public function getDetail($consulting_id, $fields = [])
    {
        if (!empty($fields)) {
            return self::find()->select($fields)->where(['id' => $consulting_id])->asArray()->one();
        }
        return self::find()->where(['id' => $consulting_id])->asArray()->one();
    }

    /**
     * 根据问题ID将问题数据插入ES中
     */
    public function insertToEs($ask_id)
    {
        $consultingInfo = ConsultingService::find()->where(['id' => $ask_id])->asArray()->one();


        if (!empty($consultingInfo)) {
            try {
                $consultingEsModel = new self();
                $consultingEsModel->setPrimaryKey($consultingInfo['id']);
                $consultingEsModel->setAttribute('id', $ask_id);
                $consultingEsModel->setAttribute('department_category_id', trim($consultingInfo['department_category_id']));
                $consultingEsModel->setAttribute('title', $this->filterText($consultingInfo['title']));
                $consultingEsModel->setAttribute('description', $this->filterText($consultingInfo['description']));
                $consultingEsModel->save();
            } catch (\Exception $e) {
                return ['code' => 0, 'msg' => $e->getMessage()];
            }
        } else {
            return ['code' => 0, 'msg' => '咨询实录问题不存在,插入ES失败!'];
        }
        return ['code' => 1, 'msg' => '咨询实录问题信息插入ES成功!'];
    }


    /**
     * 更新ES中医生数据
     */
    public function updateToEs($consulting_id)
    {
        $consultingEsModel = self::get($consulting_id);
        //如果不存在就插入ES
        if (is_null($consultingEsModel)) {
            return $this->insertToEs($consulting_id);
        } else {
            $consultingInfo = ConsultingService::find()->where(['id' => $consulting_id])->asArray()->one();
            try {
                $consultingEsModel->setAttribute('id', $consulting_id);
                $consultingEsModel->setAttribute('department_category_id', trim($consultingInfo['department_category_id']));
                $consultingEsModel->setAttribute('title', $this->filterText($consultingInfo['title']));
                $consultingEsModel->setAttribute('description', $this->filterText($consultingInfo['description']));
                $consultingEsModel->save();
            } catch (\Exception $e) {
                return ['code' => 0, 'msg' => $e->getMessage()];
            }

            return ['code' => 1, 'msg' => '问题更新ES成功!'];
        }
    }


    /**
     * 从ES中删除数据
     */
    public function deleteFromEs($consulting_id)
    {
        return self::find()->where(['id' => $consulting_id])->delete();
    }


    /**
     * 初始化时跑数据
     */
    public function initEsData($consulting_id)
    {
        $consultingInfo = ConsultingService::find()->where(['id' => $consulting_id])->asArray()->one();

        //组合数据
        $data = [];
        $data['id'] = $consulting_id;
        $data['department_category_id'] = intval($consultingInfo['department_category_id']);
        $data['title'] = $this->filterText($consultingInfo['title']);
        $data['description'] = $this->filterText($consultingInfo['description']);

        $db = self::getDb();
        $command = $db->createCommand();
        $res = $command->insert(self::index() . '_' . date('d'), '_doc', $data, $consulting_id);
        return $res;
    }

    /**
     * 过滤文本
     */
    private function filterText($content)
    {
        //过滤标签空格
        $contentStr = preg_replace("/(\s|\&nbsp\;| |\xc2\xa0)/", "", strip_tags($content));
        //过滤字符串中的\r\n 以及转义字符
        $contentStr = stripslashes(str_replace(array("\r\n", "\r", "\n"), "", $contentStr));

        return strval(trim($contentStr));
    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值