ES加索引数据添加,IK分词器高亮显示

//先将商品表的数据存进es
public function add_goods_data(){
    $data = Goods::select();
    $arr = (new Collection($data))->toArray();
    $es = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
    foreach ($arr as $k=>$v){
        $params = [
            'index'=>'goods',//库
            'type'=>'_doc',//表(额外需要注意的,这里是固定的写法)
            'id'=>$v['id'],//主键
            'body'=>$v//数据
        ];
        $r = $es->index($params);
    }
    echo 'success';
}
//先将商品表的数据存进es
    public function add_goods_data(){
        $data = Goods::select();
        $arr = (new Collection($data))->toArray();
        $es = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
        foreach ($arr as $k=>$v){
            $params = [
                'index'=>'goods',//库
                'type'=>'_doc',//表(额外需要注意的,这里是固定的写法)
                'id'=>$v['id'],//主键
                'body'=>$v//数据
            ];
            $r = $es->index($params);
        }
        echo 'success';
    }
  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);//剩下的就是前端展示的事情了

    }

 

上一篇:解决 Elastic Search 的深分页问题


下一篇:【clickhouse】clickhouse SQL 执行计划