es 简单实现增加,查询,分词 热词

看代码:

 $params = [
            'index' => "goods",
            'body' => [
                'mappings' => [
                    'properties' => [
                        //之后可以进行搜索的字段
                        'name' => [
                            'type' => 'text',
                            "analyzer" => "ik_max_word",
                            "search_analyzer" => "ik_max_word"
                        ]
                    ]
                ]
            ]
        ];
        $this->client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
//    执行 只用执行一次即可
//        $this->client->indices()->create($params);

 添加es中的表,index 表示表名 body 表示主体部分,然后执行,可以创建一个es 中的表格,相当于数据库中的数据表,现在还是空的表格,需要添加数据后在进行查询

添加:

 $goods = $goods->toArray();
        $params = [
            'index' => 'goods',
            'type' => '_doc',
            'body' => $goods
        ];
        //执行添加
        return $this->client->index($params);

先查询出添加数据库的数据,转为数组格式添加进es中 方便在随后的搜索中实现搜索

搜索:

     //判断用户是否搜索,如果没有则跳过
        if ($search != "") {
            $client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
            $params = [
                'index' => 'goods',
                'type' => '_doc',
                'body' => [
                    'query' => [
                        'match' => [
                            'name' => $search
                        ]
                    ],
                    'highlight' => [
                        'fields' => [
                            'name' => [
                                'pre_tags' => "<em style='color: red'>",
                                'post_tags' => "</em>",
                            ]
                        ]
                    ]
                ]
            ];
//            dd($params);
            // 执行搜索
            $response = $client->search($params);
//            dd($response);
            //高亮
            $data = $response['hits']['hits'];
            $res = [];
            //循环获取高亮字段
            foreach ($data as $v) {
                if (!empty($v['highlight']['name'][0])) {
                    $v['_source']['name'] = $v['highlight']['name'][0];
                }
                array_push($res, $v['_source']);
            }
//            热词
            Redis::zincrby('search', 1, $search);
            return $res;
        }
        $res = Goods::get();
//        dd($res);
        return $res;

基本实现

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值