封装一个ElasticSearch查询操作类(PHP)

<?php
namespace app\index\controller;
class Es
{
    //Es服务访问url
    private $esUrl = 'http://127.0.0.1:9200';

    //Es索引配置
    private $esIndex = [
        'index_goods' => '/index_goods/'
    ];

    //Es搜索
    public function test(){
        $keywords = input('keywords'); //搜索关键词
        $page = input('page'); //页码 从1开始
        $limit = input('limit'); //每页条数
        $conditions = [
            ['field' => 'goods_name', 'type' => '=', 'value' => $keywords],
        ];
        $offset  = ($page > 0) ? ($page - 1) * $limit : 0;
        $columns = ['goods_id','goods_name'];
        $url = $this->esUrl.$this->esIndex['index_goods'];
        $res  = self::Search($url,$conditions,$offset,$limit,$columns);
        return json($res);
    }

    /**
     * ES语法查询匹配
     * @param string $url URL
     * @param array $conditions 查询条件
     * @param int $offset 页码
     * @param int $limit 条数
     * @param array $columns 过滤字段
     * @param array $order 排序
     * @return array
     */
    public static function Search($url, $conditions, $offset, $limit, $columns=[], $order=[]){
        //构造请求参数
        $params = [
            'query'   => [
                'bool' => [
                    'must' => [
                    ],
                ],
            ],
            '_source' => $columns,
            'from'    => $offset,
            'size'    => $limit
        ];
        if (!empty($conditions)){
            foreach ($conditions as $v){
                switch($v['type']){
                    case 'between':
                        $params['query']['bool']['filter'][]['range'][$v['field']]['gt'] = intval($v['value'][0]);
                        $params['query']['bool']['filter'][]['range'][$v['field']]['lt'] = intval($v['value'][1]);
                        break;
                    case '>':
                        $params['query']['bool']['must'][]['range'][$v['field']]['gt'] = $v['value'];
                        break;
                    case '>=':
                        $params['query']['bool']['must'][]['range'][$v['field']]['gte'] = $v['value'];
                        break;
                    case '<':
                        $params['query']['bool']['must'][]['range'][$v['field']]['lt'] = $v['value'];
                        break;
                    case '<=':
                        $params['query']['bool']['must'][]['range'][$v['field']]['lte'] = $v['value'];
                        break;
                    case '=':
                        $params['query']['bool']['should'][]['match'][$v['field']] = $v['value'];
                        break;
                    case '==':
                        $params['query']['bool']['must'][]['wildcard'][$v['field']] = $v['value'];
                        break;
                    case '!=':
                        $params['query']['bool']['must_not'][]['match'][$v['field']] = $v['value'];
                        break;
                    case 'or':
                        $v['value'] = explode(",",$v['value']);
                        if (!empty($v['value']) || is_array($v['value'])){
                            foreach ($v['value'] as $m => $n){
                                $params['query']['bool']['should'][] = array(
                                    'match' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'in':
                        $v['value'] = explode(",",$v['value']);
                        if (!empty($v['value']) || is_array($v['value'])){
                            foreach ($v['value'] as $m => $n){
                                $params['query']['bool']['filter']['bool']['should'][] = 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']['filter']['bool']['must_not'][] = array(
                                    'term' => array(
                                        $v['field'] => $n,
                                    ),
                                );
                            }
                        }
                        break;
                    case 'like':
                        $params['query']['query']['bool']['must'][]['match'][$v['field']] = $v['value'];
                        unset($params['sort']);
                        $params['sort']['_score']['order'] = 'desc';
                        $params['sort']['user_id']['order'] = 'desc';
                        break;
                    default:
                        return [];
                        break;
                }
            }
        }
        //请求ES服务
        $res = self::getEs($url.'_search/', $params);
        $reData = [];
        if(!empty($res)){
            $res = json_decode($res,true);
            $reData['data'] = [];
            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;
    }

    /**
     * curl请求Es
     * @param string $url URL
     * @param array $data 请求参数
     * @param bool $is_post 是否为post请求
     * @return bool|string
     */
    public static function getEs($url, $data, $is_post = true ){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        if ($is_post) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        $result   = curl_exec($ch);
        curl_getinfo($ch, CURLINFO_HEADER_OUT);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode != 200) {
            return false;
        } else {
            return $result;
        }
    }
}
发布了103 篇原创文章 · 获赞 167 · 访问量 18万+

猜你喜欢

转载自blog.csdn.net/msllws/article/details/103265473