Elasticsearch 添加+搜索

//创建一个es层

 public function __construct()
    {
        $this->client=ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
    }

//es添加    在es类类写好封装的方法

https://www.elastic.co/guide/cn/elasticsearch/php/current/index.html
public function es($index,$type,$id,$body)
    {
        $params = [
            'index' => $index,
            'type' => $type,
            'id' => $id,
            'body' => $body,
        ];

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

//先写好正常的田间,稍作改动  

public function add()
    {
        $data = \request()->post();

        if(Cache::store('redis')->get('id') == ''){
            return json_encode(['code'=>500,'msg'=>'请先登录','data'=>'']);
        }

        $add = showModel::create($data);

        $text = [
            'text' => $add['text']
        ];
        $es = new es();
        $es->es('syt','521',$add['id'],$text);
        if ($add){
            return json_encode(['code'=>200,'msg'=>'添加成功','data'=>'']);
        }
    }

//es搜索  在es类类写好封装的方法

public function where($index,$type,$body)
    {
        $params = [
            'index' => $index,
            'type' => $type,
            'body' => [
                'query' => [
                    'match' => [
                        'body' => $body
                    ]
                ],'highlight'=>[
                    'pre_tags'=>["<span>"],
                    'post_tags'=>["</span>"],
                    'fields'=>[
                        "mes"=>new \stdClass()
                    ]
                ]
            ]
        ];

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

  先写好普通搜索 

    public function search()
    {
        $where = [];
        $text = \request()->get('text');
//        dd($text);


            $es = new es();
        $syq = $es->where('hzh','hhz',$text);
// dd($syq);
        $score=$syq['hits']['hits'];
        foreach ($score as $k=>$v){
            $score[$k]['_source']['索引关键字']=$v['highlight']['索引关键字'][0];
        }
        $title= array_column($score,'_source');
//        dd($data);
        return json_encode(['code'=>200,'msg'=>'查询成功','data'=>$title]);
    }

猜你喜欢

转载自blog.csdn.net/QiZong__BK/article/details/125426712