PHP操作ES使用案例

<?php
class search
{
    public function __construct()
    {
        $this->esUri = $host . ':' . $port . "/" . $index . "/" . $type. "/";
    }

    //demo
    public function demo()
    {
        $conditions = [
            ['field' => 'company', 'type' => 'like', 'value' => '春風(fēng)'],
            ['field' => 'groupid', 'type' => 'between', 'value' => [4, 6]],
            ['field' => 'email', 'type' => '=', 'value' => 'jiaogun@139.com'],
        ];
        $page    = 1;
        $limit   = 20;
        $offset  = ($page > 0) ? ($page - 1) * $limit : 0;
        $columns = ['username', 'userid', 'groupid', 'company'];
        $order   = array('field' => 'userid', 'sort' => 'desc');
        $res     = $this->search($conditions, $offset, $limit, $columns, $order);
        var_dump($res);die();

    }

    //es搜索
    public function search($conditions = array(), $offset = 0, $limit = 20, $columns = array(), $order = array('field' => 'userid', 'sort' => 'desc'))
    {
        $params = [
            "query"   => [
                "filtered" => [
                    'filter' => [
                        'bool' => [
                            'must' => [
                            ],
                        ],
                    ],
                    "query"  => [
                        'bool' => [
                            'must' => [

                            ],
                        ],
                    ],
                ],
            ],
            'sort'    => [
                $order['field'] => [
                    'order' => $order['sort'],
                ],
            ],
            '_source' => $columns,
            'from'    => $offset,
            'size'    => $limit,
        ];
        if (!empty($conditions)) {
            foreach ($conditions as $v) {
                switch ($v['type']) {
                    case 'between':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'][0];
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'][1];
                        break;
                    case '>':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'];
                        break;
                    case '>=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gte'] = $v['value'];
                        break;
                    case '<':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'];
                        break;
                    case '<=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lte'] = $v['value'];
                        break;
                    case '=':
                        $params['query']['filtered']['filter']['bool']['must'][]['term'][$v['field']] = $v['value'];
                        break;
                    case '!=':
                        $params['query']['filtered']['filter']['bool']['must_not'][]['term'][$v['field']] = $v['value'];
                        break;
                    case 'in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'not in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must_not'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'like':
                        $params['query']['filtered']['query']['bool']['must'][]['match'][$v['field']] = $v['value'];
                        unset($params['sort']);
                        $params['sort']['_score']['order'] = 'desc';
                        $params['sort']['userid']['order'] = 'desc';
                        break;
                    default:
                        return false;
                        break;
                }
            }
        }
        $res            = $this->getEs($params, true, $this->esUri . '_search/');
        $res            = json_decode($res, true);
        $reData['data'] = array();
        if (!empty($res['hits']['hits'])) {
            foreach ($res['hits']['hits'] as $k => $v) {
                $reData['data'][$k] = $v;
            }
        }
        $reData['count'] = !empty($res['hits']['total']) ? $res['hits']['total'] : 0;
        return $reData;
    }

    //es搜索 解決深度分頁問題 按照userid asc排序
    public function searchAll($conditions = array(), $limit = 50, $columns = array(), $userid = 0)
    {
        $params = [
            "query"   => [
                "filtered" => [
                    'filter' => [
                        'bool' => [
                            'must' => [

                            ],
                        ],
                    ],
                    "query"  => [
                        'bool' => [
                            'must' => [
                                [
                                    'range' => [
                                        'userid' => [
                                            'gt' => $userid,
                                        ],
                                    ],
                                ],
                            ],
                        ],
                    ],
                ],
            ],
            'sort'    => [
                'userid' => [
                    'order' => 'asc',
                ],
            ],
            '_source' => $columns,
            'size'    => $limit,
        ];
        if (!empty($conditions)) {
            foreach ($conditions as $v) {
                switch ($v['type']) {
                    case 'between':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'][0];
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'][1];
                        break;
                    case '>':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'];
                        break;
                    case '>=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gte'] = $v['value'];
                        break;
                    case '<':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'];
                        break;
                    case '<=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lte'] = $v['value'];
                        break;
                    case '=':
                        $params['query']['filtered']['filter']['bool']['must'][]['term'][$v['field']] = $v['value'];
                        break;
                    case '!=':
                        $params['query']['filtered']['filter']['bool']['must_not'][]['term'][$v['field']] = $v['value'];
                        break;
                    case 'in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'not in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must_not'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'like':
                        $params['query']['filtered']['query']['bool']['must'][]['match'][$v['field']] = $v['value'];
                        break;
                    default:
                        return false;
                        break;
                }
            }
        }
        $res            = $this->getEs($params, true, $this->esUri . '_search/');
        $res            = json_decode($res, true);
        $reData['data'] = array();
        if (!empty($res['hits']['hits'])) {
            foreach ($res['hits']['hits'] as $k => $v) {
                $reData['data'][$k] = $v;
            }
        }
        $reData['count'] = !empty($res['hits']['total']) ? $res['hits']['total'] : 0;
        return $reData;
    }

    //es統(tǒng)計數(shù)量
    public function count($conditions = array())
    {
        $params = [
            "query" => [
                "filtered" => [
                    'filter' => [
                        'bool' => [
                            'must' => [
                            ],
                        ],
                    ],
                    "query"  => [
                        'bool' => [
                            'must' => [

                            ],
                        ],
                    ],
                ],
            ],
        ];
        if (!empty($conditions)) {
            foreach ($conditions as $v) {
                switch ($v['type']) {
                    case 'between':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'][0];
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'][1];
                        break;
                    case '>':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'];
                        break;
                    case '>=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['gte'] = $v['value'];
                        break;
                    case '<':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'];
                        break;
                    case '<=':
                        $params['query']['filtered']['filter']['bool']['must'][]['range'][$v['field']]['lte'] = $v['value'];
                        break;
                    case '=':
                        $params['query']['filtered']['filter']['bool']['must'][]['term'][$v['field']] = $v['value'];
                        break;
                    case '!=':
                        $params['query']['filtered']['filter']['bool']['must_not'][]['term'][$v['field']] = $v['value'];
                        break;
                    case 'in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'not in':
                        if (!empty($v['value']) && is_array($v['value'])) {
                            foreach ($v['value'] as $m => $n) {
                                $params['query']['filtered']['filter']['bool']['must_not'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'like':
                        $params['query']['filtered']['query']['bool']['must'][]['match'][$v['field']] = $v['value'];
                        break;
                    default:
                        return false;
                        break;
                }
            }
        }
        $res   = $this->getEs($params, true, $this->esUri . '_count/');
        $res   = json_decode($res, true);
        $count = !empty($res['count']) ? $res['count'] : 0;
        return $count;
    }
    private function getEs($data = [], $ispost = true, $uri = "es地址")
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $uri);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        $result   = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode != 200) {
            var_dump($result);
            return false;
        } else {
            return $result;
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市楣富,隨后出現(xiàn)的幾起案子斯嚎,更是在濱河造成了極大的恐慌鉴未,老刑警劉巖计技,帶你破解...
    沈念sama閱讀 212,686評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異动分,居然都是意外死亡假消,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,668評論 3 385
  • 文/潘曉璐 我一進(jìn)店門耐床,熙熙樓的掌柜王于貴愁眉苦臉地迎上來密幔,“玉大人,你說我怎么就攤上這事撩轰】杷Γ” “怎么了昧廷?”我有些...
    開封第一講書人閱讀 158,160評論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長偎箫。 經(jīng)常有香客問我木柬,道長,這世上最難降的妖魔是什么淹办? 我笑而不...
    開封第一講書人閱讀 56,736評論 1 284
  • 正文 為了忘掉前任眉枕,我火速辦了婚禮,結(jié)果婚禮上怜森,老公的妹妹穿的比我還像新娘速挑。我一直安慰自己,他們只是感情好副硅,可當(dāng)我...
    茶點故事閱讀 65,847評論 6 386
  • 文/花漫 我一把揭開白布姥宝。 她就那樣靜靜地躺著,像睡著了一般恐疲。 火紅的嫁衣襯著肌膚如雪腊满。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 50,043評論 1 291
  • 那天流纹,我揣著相機與錄音糜烹,去河邊找鬼。 笑死漱凝,一個胖子當(dāng)著我的面吹牛疮蹦,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播茸炒,決...
    沈念sama閱讀 39,129評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼愕乎,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了壁公?” 一聲冷哼從身側(cè)響起感论,我...
    開封第一講書人閱讀 37,872評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎紊册,沒想到半個月后比肄,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,318評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡囊陡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,645評論 2 327
  • 正文 我和宋清朗相戀三年芳绩,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片撞反。...
    茶點故事閱讀 38,777評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡妥色,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出遏片,到底是詐尸還是另有隱情嘹害,我是刑警寧澤撮竿,帶...
    沈念sama閱讀 34,470評論 4 333
  • 正文 年R本政府宣布,位于F島的核電站笔呀,受9級特大地震影響幢踏,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜凿可,卻給世界環(huán)境...
    茶點故事閱讀 40,126評論 3 317
  • 文/蒙蒙 一惑折、第九天 我趴在偏房一處隱蔽的房頂上張望授账。 院中可真熱鬧枯跑,春花似錦、人聲如沸白热。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,861評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽屋确。三九已至纳击,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間攻臀,已是汗流浹背焕数。 一陣腳步聲響...
    開封第一講書人閱讀 32,095評論 1 267
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留刨啸,地道東北人堡赔。 一個月前我還...
    沈念sama閱讀 46,589評論 2 362
  • 正文 我出身青樓,卻偏偏與公主長得像设联,于是被迫代替她去往敵國和親善已。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,687評論 2 351

推薦閱讀更多精彩內(nèi)容