yii2中使用elasticsearch

elastic官网的操作类
https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_configuration.html
composer.json的require中加入:
"elasticsearch/elasticsearch": "~6.0"
composer update
config/params.php中添加
'elasticsearch' => [
'192.168.163.128:9200'
],
新建EsService.php

namespace app\modules\study\service;

use Elasticsearch\ClientBuilder;
use  Yii;

class EsService
{
    public  $index;
    public  $type;
    public  $client;
    public   function __construct($index, $type)
    {
        $this->index = $index;
        $this->type = $type;
        $hosts = yii::$app->params['elasticsearch'];
        $this->client = ClientBuilder::create()->setHosts($hosts)->build();
    }

    /**
     * @param xx
     * @desc 创建索引
     */
    public function createIndex()
    {
        $params = [
            'index' => $this->index,
            'body' => [
                'settings' => [
                    'number_of_shards' => 2,
                    'number_of_replicas' => 0
                ]
            ]
        ];

        $response = $this->client->indices()->create($params);
        return $response;
    }

    /**
     * @param xx
     * @desc 删除索引
     */
    public function deleteIndex()
    {
        $params = ['index' => $this->index];
        $response = $this->client->indices()->delete($params);
        return $response;
    }

    /**
     * @param $id
     * @param $data
     * @desc 添加文档
     */
    public function createDocument($id, $data)
    {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'id' => $id,
            'body' => $data
        ];

        $response = $this->client->index($params);
        return $response;
    }

    
    /**
     * @param $data
     * @return array
     * 批量添加文档
     */
    public function batchCreateDoc($data)
    {
        foreach ($data as  $value){
            $params = [
                'index' => $this->index,
                'type' => $this->type,
                'body' => $value
            ];
            $responses = $this->client->index($params);
        }

        return $responses;
    }

    /**
     * @param $id
     * @desc 查询文档
     */
    public function getDocument($id)
    {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'id' => $id,
            'client' => [ 'ignore' => [400, 404] ],
        ];

        $response = $this->client->get($params);
        return $response;
    }

    /**
     * @param $param
     * @desc 搜索文档
     */
    public function searchDocument($param)
    {
        $tmp = [];
        foreach ($param as $key => $value) {
            $tmp[$key] = [
            "query"=> $value,
            "minimum_should_match"=> "50%",
          ];
        }

        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'body' => [
                'query' => [
                    'match' =>  $tmp
                ]
            ]
        ];

        $response = $this->client->search($params);
        return $response;
    }

    /**
     * @param $param
     * @desc 关键词搜索文档
     */
     public function keywordSearch($keyword)
    {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'body' => [
                'query' => [
                    'multi_match' =>  [
                        'query'=>$keyword,
                    ],
                ]
            ]
        ];
        $response = $this->client->search($params);
        return $response;
    }


    /**
     * @param $param
     * @desc fuzzy模糊搜索文档
     */
    public function fuzzySearch($param)
    {

        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'body' => [
                'query' => [
                    'fuzzy' =>  $param
                ]
            ]
        ];

        $response = $this->client->search($params);
        return $response;
    }

    /**
     * @param $param
     * @desc编辑文档
     */
    public function editDocument($id, $data)
    {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'id' => $id,
            'body' => [
                'doc' => $data
            ]
        ];

        $response = $this->client->update($params);
        return $response;
    }

   # mapping配置
    public function mapping($properties)
    {
        $params = [
            'index' => $this->index,
            'body' => [
                'settings' => [
                    'number_of_shards' => 2,
                    'number_of_replicas' => 0
                ],
                'mappings' => [
                    $this->type => [
                        '_source' => ['enabled' => true],
                        'properties' => $properties
                    ]
                ]
            ]
        ];

        $response = $this->client->indices()->create($params);
        return $response;
    }

    # 修改现有mapping
    public function updMapping($properties)
    {
        $params = [
            'index' => $this->index,
            'type' => $this->type,
            'body' => [
                $this->type => [
                    '_source' => ['enabled' => true],
                    'properties' => $properties
                ]
            ]
        ];

        $response = $this->client->indices()->putMapping($params);
        return $response;
    }

    /**
     * @return array
     * 获取mapping
     */
    public function getMapping()
    {
        $params = [
            'index' => $this->index,
        ];

        $response = $this->client->indices()->getMapping($params);
        return $response;
    }

}

控制器操作

namespace app\modules\study\controllers;

use app\modules\study\service\EsService;
use yii\web\Controller;
use app\modules\study\models\Es;

class EsController extends Controller
{
    public function actionIndex()
    {
        $es = new EsService('china','city');
        //$result = $es->getDocument(3);
        //$result = $es->searchDocument(['title'=>'java2']);
        //$result = $es->fuzzySearch(['title'=>'java']);
        $result = $es->keywordSearch('北京');

      /*$param = [
           [
               'name' => '太原',
               'people' => 1000
           ],
           [
               'name' => '成都',
               'people' => 1500
           ],
           [
               'name' => '武汉',
               'people' => 1800
           ]

        ];
        //批量添加
        $result = $es->batchCreateDoc($param);*/

        /*$properties = [
            'citytid'  => ['type' => 'integer'],
            'name' => ['type' => 'text'],
            'people' => ['type' => 'integer'],
            'address' => ['type' => 'text']
        ];*/

        //$result = $es->mapping($properties);
        //$result = $es->getMapping();

        //可以添加字段,但原有字段是不能修改类型的,原因是:
        //一个字段的类型修改以后,那么该字段的所有数据都需要重新索引。Elasticsearch底层使用的是lucene库,字段类型修改以后索引和搜索要涉及分词方式等操作,不允许修改类型是符合lucene机制的。
//        $result = $es->updMapping($properties);
        
        echo '
';
        print_r($result);
        exit;
    }
}


yii2的操作类
1 引入elasticsearch操作类
composer.json的require中添加
"yiisoft/yii2-elasticsearch": "~2.0.0"
composer update

2 config/web.php的components中添加

'components' => [
     ...
        'elasticsearch' => [
            'class' => 'yii\elasticsearch\Connection',
            'nodes' => [
                ['http_address' => '192.168.163.128:9200']
            ],
            'autodetectCluster' => false
        ],
        ...
    ],

3 新建model类

namespace app\modules\study\models;

use yii\elasticsearch\ActiveRecord;

class Es extends ActiveRecord
{
    public static $currentIndex;


    # 定义db链接
    public static function getDb()
    {
        return \Yii::$app->get('elasticsearch');
    }


    # 索引
    public static function index()
    {
        return 'lib';
    }

    # 类型
    public static function type()
    {
        return 'books';
    }


    /**
     * Create this model's index
     */
    public static function createIndex()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $command->createIndex(static::index(), [
            'settings' => [ 'index' => ['refresh_interval' => '1s'] ],
            'mappings' => static::mapping(),
            //'warmers' => [ /* ... */ ],
            //'aliases' => [ /* ... */ ],
            //'creation_date' => '...'
        ]);
    }


    /**
     * Delete this model's index
     */
    public static function deleteIndex()
    {
        $db = static::getDb();
        $command = $db->createCommand();
        $command->deleteIndex(static::index(), static::type());
    }

    public static function updateRecord($productid, $columns){
        try {
            $record = self::get($productid);
            foreach($columns as $key => $value){
                $record->$key = $value;
            }
            return $record->update();
        }catch (\Exception $e){
            return false;
        }
    }

    //删除记录
    public static function deleteRecord($productid){
        try {
            $record = self::get($productid);
            $record->delete();
            return true;
        }catch (\Exception $e){
            return false;
        }
    }

    //保存数据(添加 || 更新)
    public function saveRecord($data){

        //加载数据
        if ($this->load($data) && $this->validate()){
            $isExist = false;
            try {
                $record = self::get($this->productid);
                //不存在 为更新
                if (!$record){
                    $record = new self();
                    $record->setPrimaryKey($this->productid);
                }else{
                    $isExist = true;
                }
            }catch (\Exception $e){
                $record = new self();
                $record->setPrimaryKey($this->productid);
            }
            //遍历数据到对象
            foreach ($data['Es'] as $key => $value) {
                $record->$key = $value;
            }

            try {

                if (!$isExist){
                    //插入
                    $result = $record->insert();
                }else{
                    //更新
                    $result = $record->update();
                }

            }catch (\Exception $e){
                return false;

            }
            return true;
        }
    }


    # 属性
    public function attributes()
    {
        $mapConfig = self::mapConfig();
        return array_keys($mapConfig['properties']);
    }

    public function rules()
    {
        return [
            [["productid","title"],'required']
        ];
    }


    # mapping配置
    public static function mapConfig()
    {
        return [
            'properties' => [
                'productid'  => ['type' => 'double'],
                'title' => ['type' => 'string','analyzer'=>'ik'],
                'price' => ['type' => 'double']
            ]
        ];
    }

    public static function mapping()
    {
        return [
            static::type() => self::mapConfig(),
        ];
    }

    /**
     * Set (update) mappings for this model
     */
    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());
    }

    public static function getMapping()
    {
        $db = self::getDb();
        $command = $db->createCommand();
        return $command->getMapping();
    }


}

4 控制器中操作

namespace app\modules\study\controllers;

use yii\web\Controller;
use app\modules\study\models\Es;

class EsController extends Controller
{
   //查询
    public function actionTest(){
        $keyword = "java2";
        $res = Es::find()->query([
            "term" => ['title'=>'java'],
            //"multi_match" => [
                //"query" => $keyword,
               // "fields" => ["title"] //检索属性
           //],
        ])->asArray()->all();

        echo '
';
        print_r($res);
        exit;

    }

    //创建 或更新
    public function actionAdd(){
        $ESArray = [
            'Es' => [
                'productid' => '4',
                'title' => 'php2',
                'price' => '22'
            ]
        ];

        $es = new Es();
        if(!$es->saveRecord($ESArray)){
            throw new \Exception("操作失败");
        }

        echo "操作成功";

    }

    //删除
    public function actionDelete($id){

        $es = new Es();
        if(!$es->deleteRecord($id)){
            throw new \Exception("删除失败");
        }
        echo "操作成功";

    }

}

你可能感兴趣的:(yii2中使用elasticsearch)