• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

null

开发技术 开发技术 3小时前 2次浏览

1.安装

2.运行

3.框架内安装扩展包

4.创建索引

public function create_index(){
        //创建es实例
        $es = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
        $params = [
            'index' => '索引名称',//类似于库名
            'body' => [
                'settings' => [
                    'number_of_shards' => 3,
                    'number_of_replicas' => 2
                ],
                'mappings' => [
                    '_source' => [
                        'enabled' => true
                    ],
                    'properties' => [
               //之后可以进行搜索的字段 '字段名称' => [ 'type' => 'text', "analyzer" => "ik_max_word", "search_analyzer" => "ik_max_word" ] ] ] ] ]; //执行创建 $r = $es->indices()->create($params); dump($r); }

5.填充数据

public function add_goods_data(){
        $data = GoodsModel::select();
        $arr = (new Collection($data))->toArray();
        $es = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
        foreach ($arr as $k=>$v){
            $params = [
                'index'=>'goodslists_index',//库
                'type'=>'_doc',//表(额外需要注意的,这里是固定的写法)
                'id'=>$v['id'],//主键
                'body'=>$v//数据
            ];
            $r = $es->index($params);
        }
        echo 'success';
    }

6.搜索  代码过多可以再次创建一个控制器

public function search_test(){
        $word = input('word');//接收关键字
        $page = input('page',1);//接收当前页(如果没接收到,默认是1)
        $size = 5;//每页显示条数
        $limit = ($page-1)*$size;//偏移量
        $client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();//创建es实例
        //设置查询的条件
        $params = [
            'index' => 'goodslists_index',//索引(类似于库)
            //'type' => '_doc',
            'body' => [
                //查询内容
                'query' => [
                    'match' => [//匹配
                        'goods_name' => $word//匹配字段
                    ]
                ],
                'highlight' => [//高亮
                    'pre_tags' => ["<em style='color: red'>"],//样式自己写
                    'post_tags' => ["</em>"],
                    'fields' => [
                        "goods_name" => new stdClass()
                    ]
                ]
            ]
        ];
        //分页限制
        $params["size"] = $size;//每页显示条数
        $params["from"] = $limit;//偏移量
        $results = $client->search($params);//es搜索
        foreach ($results['hits']['hits'] as $k=>$v){
            $results['hits']['hits'][$k]['_source']['goods_name'] = $v['highlight']['goods_name'][0];
        }

        $data = array_column($results['hits']['hits'],'_source');

        $arr['data'] = $data;//数据
        $arr['page'] = $page;//当前页
        $arr['total'] = $results['hits']['total']['value'];//总条数
        $arr['last_page'] = ceil($results['hits']['total']['value']/$size);//总页数

        print_r($arr);

    }

程序员灯塔
转载请注明原文链接:null
喜欢 (0)