php+elasticsearch+多字段搜索操作懒人版

本文介绍如何使用Elasticsearch进行索引创建、数据添加及多字段搜索,并实现了中文分词配置和搜索结果高亮显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://localhost:9200/
运行目录下的elasticsearch.bat
运行目录下的elasticsearch.bat
在这里插入图片描述
出现started进入http://localhost:9200/
在这里插入图片描述
首先单例模式封装es连接

private static $EsClient = false;

    //私有的构造方法
    private function __construct()
    {

    }

    //3.私有的克隆方法
    private function __clone()
    {

    }

    //公有的静态方法
    public static function getIntance()
    {
        if (self::$EsClient == false) {
            self::$EsClient = ClientBuilder::create()->build();
        }
        return self::$EsClient;
    }

Es控制器

    static $es;
    static $search_filed=['comment','create_at'];
    static $index="user";

    /**
     * es索引创建
     */
    public function esCreate()
    {
        $client  = EsController::getIntance();;
        $search_filed=self::$search_filed;
        $properties=[];
        foreach ($search_filed as $k=>$v){//中文分词器配置
            $properties[$v]=[
                'type' =>"text",  //这是一种搜索的格式 自己可以了解一下参数
                "analyzer" => "ik_max_word",
                "search_analyzer" => "ik_max_word"
            ];
        }
        $params = [
            'index' => self::$index,//类似于库名
            'body' => [
                //这里是权重值 你自己根据需求加入
                'settings' => [
                    'number_of_shards' => 3,
                    'number_of_replicas' => 2
                ],
                'mappings' => [
                    '_source' => [
                        'enabled' => true
                    ],
                    'properties' =>$properties
                ]
            ]
        ];
        //执行创建
        $r = $client->indices()->create($params);
    }

    /**
     * @throws \think\exception\DbException
     * es数据添加
     * ++待批量入++
     */
    public function esAdd()
    {
        $client  = EsController::getIntance();;
        $data = json_decode(json_encode(Comment::all()), true);
        foreach ($data as $k => $v) {
            $params = [
                'index' => self::$es,//你上面创建的库
                'type' => '_doc',//表(额外需要注意的,这里是固定的写法)
                'id' => $v['id'],//主键
                'body' => $v//数据
            ];
            $r = $client->index($params);
        }
    }

    /**
     * @param Request $request
     * @return \think\response\Json
     * es搜素多字段搜索
     */
    public function esSearch(Request $request)
    {
        $client  = EsController::getIntance();;
        $word = $request->get('word');//接收关键字
        $search_filed=self::$search_filed;
        if(empty($word)){
            $body=[];
        }else{
            $fields=[];
            $should=[];
            foreach ($search_filed as $k=>$v){
                $fields[]=[$v=>new \stdClass()];
                $should[]=['match' => [$v => $word]];
            }
            $body=[
                'query' => [
                    //bool 关键字: 用来组合多个条件实现复杂查询
                    'bool' => [
                        //bool 查询如果不加  should 就是多个字段必须全部填写 才能查询  should: 相当于|| 成立一个就行
                        "should" =>$should
                    ]
                ],
                'highlight' => [//高亮
                    'pre_tags' => ["<em style='color: red'>"],//样式自己写
                    'post_tags' => ["</em>"],
                    'fields' =>$fields
                ]
            ];
        }
        $params = [
            'index' => self::$index,//索引(跟上面你填写的数据库一样)
            //'type' => '_doc',
            'body' =>$body
        ];
        $results = $client->search($params);//es搜索
        if (!empty($word)){
            foreach ($results['hits']['hits'] as $k => $v) {
                //判断 对应的字段是否为空 如果不为空 就进行一个赋值 然后进行搜索
                foreach ($search_filed as $kk=>$vv){
                    if (!empty($v['highlight'][$vv][0])) {
                        $results['hits']['hits'][$k]['_source'][$vv] = $v['highlight'][$vv][0];
                    }
                }
            }
        }
        // 这里  array_column 取出数组的某一列 数据都在  _source 里面
        $data = array_column($results['hits']['hits'], '_source');
        return $data;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值