elasticsearch之PHP封裝類

elasticsearch-php 類封裝

<?php
/**
 * elasticsearch封裝類
 * @author joniding
 * @date 2019-07-19
 */
namespace PhpLib\Ec\Helpers;

use Elasticsearch\ClientBuilder;
use Illuminate\Http\Request;

class ElasticSearch
{
    public $config;
    public $api;
    public $index_name;
    public $index_type;

    public function __construct($index_name,$index_type)
    {
        try{
            //加載配置文件
            $this->config = config('elasticsearch');
            //構(gòu)建客戶端對象
            $this->api = ClientBuilder::create()->setHosts($this->config['hosts'])->build();

            $this->index_name = $index_name;
            $this->index_type = $index_type;
        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 初始化索引參數(shù)
     * @author joniding
     * @return array
     */
    public function initParams()
    {
        return [
            'index' => $this->index_name,
            'type'  => $this->index_type,
        ];
    }

    /**
     * 創(chuàng)建一個索引
     * @author joniding
     * @param $settings
     * @return array
     * @throws \Exception
     */
    public function createIndex($settings = [])
    {
        try{
            $initParams['index'] = $this->index_name;
            !empty($settings) && $initParams['body']['settings'] = $settings;

            $res = $this->api->indices()->create($initParams);

        }catch(\Exception $e){
            throw $e;
        }

        return $res;
    }

    /**
     * 更新索引的映射 mapping
     * @author joniding
     * @param $data
     * @return array
     * @throws \Exception
     */
    public function setMapping($data)
    {
        try{
            $initParams = $this->initParams();
            $initParams['body'] = $data;

            $res = $this->api->indices()->putMapping($initParams);
        }catch (\Exception $e){
            throw $e;
        }
        return $res;
    }

    /**
     * 獲取索引映射 mapping
     * @author joniding
     * @return array
     * @throws \Exception
     */
    public function getMapping()
    {
        try{
            $initParams = $this->initParams();
            $res = $this->api->indices()->getMapping($initParams);
        }catch (\Exception $e){
            throw $e;
        }

        return $res;
    }

    /**
     * 向索引中插入數(shù)據(jù)
     * @author joniding
     * @param $data
     * @return bool
     * @throws \Exception
     */
    public function add($data)
    {
        try{
            $params = $this->initParams();
            isset($data['id']) && $params['id'] = $data['id'];
            $params['body'] = $data['body'];

            $res = $this->api->index($params);
        }catch (\Exception $e){
            throw $e;
        }
        if (!isset($res['_shards']['successful']) || !$res['_shards']['successful']){
            return false;
        }
        return true;
    }

    /**
     * 批量插入數(shù)據(jù)
     * @author joniding
     * @param $data
     * @return array
     * @throws \Exception
     */
    public function bulk($data)
    {
        try{
            if (empty($data['body'])) return false;
            $params = $this->initParams();
            $params['body'] = $data['body'];

            $res = $this->api->bulk($params);

        }catch (\Exception $e){
            throw $e;
        }
        return $res;
    }

    /**
     * 檢測文檔是否存在
     * @param $id
     * @return array|bool
     * @throws \Exception
     */
    public function IndexExists($id)
    {
        try{
            $params = $this->initParams();
            $params['id'] = $id;

            $res = $this->api->exists($params);

        }catch (\Exception $e){
            throw $e;
        }
        return $res;
    }


    /**
     * 單字段模糊查詢
     * 滿足單個字段查詢(不帶分頁+排序)match 分詞查詢
     * @author joniding
     * @param $data
     * @return array
     * @throws \Exception
     */
    public function search($data = [])
    {
        try{
            $params = $this->initParams();

            if (!empty($data)){
                $field = key($data);
                $query = [
                    'match' => [
                        $field => [
                            'query' => $data[$field],
                            'minimum_should_match'  => '90%'  //相似度,匹配度
                        ]
                    ]
                ];
                $params['body']['query']        = $query;
            }
            $res = $this->api->search($params);

        }catch (\Exception $e){
            throw $e;
        }
        return $res;
    }

    /**
     * 根據(jù)唯一id查詢數(shù)據(jù)
     * @author joniding
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function searchById($id)
    {
        try{
            $params = $this->initParams();
            $params['id'] = $id;

            $res = $this->api->get($params);
        }catch (\Exception $e){
            throw $e;
        }
        return $res;
    }



    /**
     * 根據(jù)關(guān)鍵字查詢數(shù)據(jù)
     * 多個字段查詢:multi_match
     * @author joniding
     * @param $data
     * $data['condition'] 條件組合
     * $data['es_size'] 每頁顯示數(shù)量
     * $data['es_from'] 從第幾條開始
     * $data['es_sort_field'] 自定義排序字段
     * @return array|bool
     * @throws \Exception
     */
    public function searchMulti($data = [])
    {
        try{
          
            if (!is_array($data)){
                return [];
            }
            $params = $this->initParams();
            if (array_key_exists('fields',$data)){
                $params['_source'] = $data['fields'];
            }

            //分頁
            if (array_key_exists('page_size',$data)){
                $params['size'] = !empty($data['page_size'])?$data['page_size']:1;
                //前端頁碼默認傳1
                $params['from'] = !empty($data['page'])?($data['page']-1)*$params['size']:0;
                unset($data['page_size'],$data['page']);
            }
            //排序
            if (array_key_exists('sort_field',$data)){
                $sort_file = !empty($data['sort_field'])?$data['sort_field']:'total_favorited';
                $sort_rule = !empty($data['sort_rule'])?$data['sort_rule']:'desc';
                $params['body']['sort'][] = [
                    ''.$sort_file.'' => [
                        'order' => ''.$sort_rule.'',
                    ]
                ];
                unset($data['sort_field'],$data['sort_rule']);
            }else{
//                $params['body']['sort'][] = [
//                    'created_at' => [
//                        'order' => 'desc',
//                    ]
//                ];
            }
            /**
             * 深度(滾動)分頁
             */
            if (array_key_exists('scroll',$data)){
                $params['scroll'] = $data['scroll'];
            }

            //條件組合
            if (array_key_exists('condition',$data)){
                $query     = [];
                $condition = $data['condition'];

                /**
                 * 組合查詢
                 */
                if (array_key_exists('bool',$condition)){
                    //必須滿足
                    if (array_key_exists('must',$condition['bool'])){
                        foreach ($condition['bool']['must'] as $key => $val){
                            if (is_array($val)){
                                $query['bool']['must'][]['range'] = [
                                    $key => [
                                        'gte'  => $val[0],
                                        'lte'    => $val[1]
                                    ]
                                ];
                            }else{
                                $query['bool']['must'][]['match'] = [
                                    $key => $val
                                ];
                            }
                        }
                    }
                }
               !empty($query) && $params['body']['query'] = $query;
            }
            $res = $this->api->search($params);
        }catch (\Exception $e){
            throw $e;
        }

        return $res;
    }

    /**
     * 查詢索引是否存在
     * @return array|bool
     * @throws \Exception
     */
    public function exist()
    {
        try{
            $params['index'] = $this->index_name;

            $res = $this->api->indices()->exists($params);

        }catch (\Exception $e){
            throw $e;
        }
        return $res;
    }


    /**
     * 根據(jù)唯一id刪除
     * @author joniding
     * @param $id
     * @return bool
     * @throws \Exception
     */
    public function delete($id)
    {
        try{
            $params       = $this->initParams();
            $params['id'] = $id;

            $res = $this->api->delete($params);
        }catch (\Exception $e){
            throw $e;
        }
        if (!isset($res['_shards']['successful'])){
            return false;
        }
        return true;
    }

    /**
     * 聚合統(tǒng)計,方差
     * @param $data
     * @return array
     * @throws \Exception
     * @author:joniding
     * @date:Times
     */
    public function searchAggs($data)
    {
        try{
            if (!is_array($data)){
                return [];
            }
            $query= [];
            $params = $this->initParams();
            $params['size'] = 0;

            /**
             * 條件組合過濾,篩選條件
             */
            if (array_key_exists('condition',$data)){
                $condition = $data['condition'];
                if (array_key_exists('bool',$condition)){
                    //必須滿足
                    if (array_key_exists('must',$condition['bool'])){
                        foreach ($condition['bool']['must'] as $key => $val){
                            if (is_array($val)){
                                $query['bool']['must'][]['range'] = [
                                    $key => [
                                        'gte'  => $val[0],
                                        'lte'  => $val[1]
                                    ]
                                ];
                            }else{
                                $query['bool']['must'][]['match'] = [
                                    $key => $val
                                ];
                            }
                        }
                        $params['body']['query'] = $query;
                    }
                }
            }

            //分組模叙、排序設置
            if (array_key_exists('agg',$data)){
                $agg = [];
                //字段值
                if (array_key_exists('terms',$data['agg'])){
                    $agg['_result']['terms'] = [
                        'field'   => $data['agg']['terms'],
                        'size'    => 500,
                    ];
                    if (array_key_exists('order',$data['agg'])){
                        foreach ($data['agg']['order'] as $key => $val){
                            $fields = 'result.'.$key;
                            $agg['_result']['terms']['order'] = [
                                $fields => $val
                            ];
                            unset($fields);
                        }
                    }
                }
                //統(tǒng)計
                if (array_key_exists('field',$data['agg'])){
                    $agg['_result']['aggs'] = [
                        'result' => [
                            'extended_stats' => [
                                'field'  => $data['agg']['field']
                            ]
                        ]
                    ];
                }

                //日期聚合統(tǒng)計
                if (array_key_exists('date',$data['agg'])){
                    $date_agg = $data['agg']['date'];
                    //根據(jù)日期分組
                    if (array_key_exists('field',$date_agg)){
                        $agg['result'] = [
                            'date_histogram' => [
                                'field'     => $data['agg']['date']['field'],
                                'interval'  => '2h',
                                'format'    => 'yyyy-MM-dd  HH:mm:ss'
                            ]
                        ];
                    }

                    if (array_key_exists('agg',$date_agg)){
                        //分組

                       if (array_key_exists('terms',$date_agg['agg'])){
                           $agg['result']['aggs']['result']['terms'] = [
                               'field' => $date_agg['agg']['terms'],
                               'size'  => 100,
                           ];
                       }
                       //統(tǒng)計最大迈倍、最小值等
                       if (array_key_exists('stats',$date_agg['agg'])){
                           $agg['result']['aggs']['result']['aggs'] = [
                                    'result_stats' => [
                                        'extended_stats' => [
                                            'field' => $date_agg['agg']['stats']
                                        ]
                                    ]
                           ];
                       }
                    }

                }
                $params['body']['aggs'] = $agg;
            }
            \Log::info(json_encode($params));
            $res = $this->api->search($params);

        }catch (\Exception $e){
            throw $e;
        }
        return $res;
    }

    /**
     * 批量查詢,只能根據(jù)id來查
     * @param $data
     * @return array
     * @throws \Exception
     * @author:joniding
     * @date:2019/8/5 19:51
     */
    public function mGet($data)
    {
        try{
            if (!is_array($data)) return [];
            //初始化索引
            $params = $this->initParams();

            if (array_key_exists('fields',$data)){
                $query['ids'] = $data['fields'];
                $params['body'] = $query;
            }
            $res = $this->api->mget($params);
            return $res;

        }catch (\Exception $e){
            throw $e;
        }
    }

    /**
     * 深度分頁
     * @param $data
     * @return array
     * @throws \Exception
     * @author:joniding
     * @date:2019/8/16 14:49
     */
    public function scroll($data)
    {
        try{
            $params = [
                'scroll_id' => $data['scroll_id'],
                'scroll'    => '1m'
            ];

            $res = $this->api->scroll($params);
//            \Log::info(json_encode($params));

            if (isset($res['_scroll_id']) && $res['_scroll_id'] != $data['scroll_id']){
                $this->api->clearScroll(['scroll_id' => $data['scroll_id'] ]);
            }

            return $res;
        }catch(\Exception $e){
            throw $e;
        }
    }


}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末戴卜,一起剝皮案震驚了整個濱河市逾条,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌叉瘩,老刑警劉巖膳帕,帶你破解...
    沈念sama閱讀 212,718評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡危彩,警方通過查閱死者的電腦和手機攒磨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,683評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來汤徽,“玉大人娩缰,你說我怎么就攤上這事≮烁” “怎么了拼坎?”我有些...
    開封第一講書人閱讀 158,207評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長完疫。 經(jīng)常有香客問我泰鸡,道長,這世上最難降的妖魔是什么壳鹤? 我笑而不...
    開封第一講書人閱讀 56,755評論 1 284
  • 正文 為了忘掉前任盛龄,我火速辦了婚禮,結(jié)果婚禮上芳誓,老公的妹妹穿的比我還像新娘余舶。我一直安慰自己,他們只是感情好锹淌,可當我...
    茶點故事閱讀 65,862評論 6 386
  • 文/花漫 我一把揭開白布匿值。 她就那樣靜靜地躺著,像睡著了一般赂摆。 火紅的嫁衣襯著肌膚如雪挟憔。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 50,050評論 1 291
  • 那天库正,我揣著相機與錄音曲楚,去河邊找鬼。 笑死褥符,一個胖子當著我的面吹牛龙誊,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播喷楣,決...
    沈念sama閱讀 39,136評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼趟大,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了铣焊?” 一聲冷哼從身側(cè)響起逊朽,我...
    開封第一講書人閱讀 37,882評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎曲伊,沒想到半個月后叽讳,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體追他,經(jīng)...
    沈念sama閱讀 44,330評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,651評論 2 327
  • 正文 我和宋清朗相戀三年岛蚤,在試婚紗的時候發(fā)現(xiàn)自己被綠了邑狸。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,789評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡涤妒,死狀恐怖单雾,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情她紫,我是刑警寧澤硅堆,帶...
    沈念sama閱讀 34,477評論 4 333
  • 正文 年R本政府宣布,位于F島的核電站贿讹,受9級特大地震影響渐逃,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜围详,卻給世界環(huán)境...
    茶點故事閱讀 40,135評論 3 317
  • 文/蒙蒙 一朴乖、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧助赞,春花似錦、人聲如沸袁勺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,864評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽期丰。三九已至群叶,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間钝荡,已是汗流浹背街立。 一陣腳步聲響...
    開封第一講書人閱讀 32,099評論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留埠通,地道東北人赎离。 一個月前我還...
    沈念sama閱讀 46,598評論 2 362
  • 正文 我出身青樓,卻偏偏與公主長得像端辱,于是被迫代替她去往敵國和親梁剔。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 43,697評論 2 351