PHP *** 作 ElasticSearch 7.X

PHP  *** 作 ElasticSearch 7.X,第1张

PHP *** 作 ElasticSearch 7.X

1,安装 扩展: composer require elasticsearch/elasticsearch:v7.10.0

2,代码展示:

class EsController{
    private $client;
    const INDEX_NAME = 'test';      //  索引名称

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

    
    public function create_index() {
        $params = [
            'index' => self::INDEX_NAME,
            'body' => [
                'settings' => [
                    'number_of_shards' => 5,   // 数据分片数,默认为5,有时候设置为3
                    'number_of_replicas' => 0  // 数据备份数,如果只有一台机器,设置为0
                ],
                'mappings'=>[
                    '_source' => [
                        'enabled' => true
                    ],
                    'properties' => [
                        'id' => [
                            'type' => 'integer',
                            'index' => false,  //index参数作用是控制当前字段是否被索引,默认为true,false表示不记录,即不可被搜索
                        ],
                        'title' => [
                            'type' => 'text', // text 类型的字符串是可以被全文检索的,它会被分词器作用,
                            'index' => true,
                            'analyzer' => 'ik_max_word' // 会将文本做最细粒度的拆分,比如会将“中华人民共和国国歌”拆分为“中华人民共和国,中华人民,中华,华人,人民共和国,人民,人,民,共和国,共和,和,国国,国歌”,会穷尽各种可能的组合,适合 Term Query
                        ],
                        'content' => [
                            'type' => 'text',
                            'index' => true,
                            'analyzer' => 'ik_max_word'
                        ],
                        'tags' => [   // 商品标签,字段被拆分后不具有意义,所以使用keyword 类型
                            'type' => 'keyword',
                        ],
                        'price' => [
                            'type' => 'float'
                        ],
                        'add_time' => [
                            'type' => 'integer',   // 时间戳
                        ],
                        'update_time' => [
                            'type' => 'integer',   // 时间戳
                        ]
                    ]
                ]
            ]
        ];

        try {
            return $this->client->indices()->create($params);
        } catch (BadRequest400Exception $e) {
            $msg = $e->getMessage();
            $msg = json_decode($msg,true);
            return $msg;
        }
    }

    
    public function delete_index() {
        $params = ['index' => self::INDEX_NAME];
        $response = $this->client->indices()->delete($params);
        return $response;
    }


    
    public function get_mapping() {
        $params = [
            'index' => self::INDEX_NAME,
        ];
        $response = $this->client->indices()->getMapping($params);
        return $response;
    }

    
    public function add_doc($id,$doc) {
        $params = [
            'index' => self::INDEX_NAME,
            'id' => $id,
            'body' => $doc
        ];
        $response = $this->client->index($params);
        return $response;
    }

    
    public function exists_doc($id = 1) {
        $params = [
            'index' => self::INDEX_NAME,
            'id' => $id
        ];
        $response = $this->client->exists($params);
        return $response;
    }

    
    public function get_doc($id = 1) {
        $params = [
            'index' => self::INDEX_NAME,
            'id' => $id
        ];
        $response = $this->client->get($params);
        return $response;
    }

    
    public function update_doc($id,$doc) {
        //在 Elasticsearch 中文档是 不可改变 的,不能修改它们。相反,如果想要更新现有的文档,需要 重建索引 或者进行替换, 我们可以使用相同的 index API 进行实现
        $params = [
            'index' => self::INDEX_NAME,
            'id' => $id,
            'body' => $doc
        ];
        $response = $this->client->index($params);
        return $response;
    }

    
    public function delete_doc($id = 1) {
        $params = [
            'index' => self::INDEX_NAME,
            'id' => $id
        ];
        $response = $this->client->delete($params);
        return $response;
    }

    // 查询文档 (分页,排序,权重,过滤)
    public function search_doc($keywords = "电脑",$from = 0,$size = 2) {
        $params = [
            'index' => self::INDEX_NAME,
            'body' => [
                'query' => [
                    'bool' => [
                        'should' => [
                            ['match' =>
                                [
                                    'title' => [
                                        'query' => $keywords,
                                        'boost' => 3, // 权重大
                                    ]
                                ]
                            ],
                            ['match' =>
                                [
                                    'content' => [
                                        'query' => $keywords,
                                        'boost' => 2,
                                    ]
                                ]
                            ],
                        ],
                    ],
                ],
                'sort' => ['price'=>['order'=>'desc']]
                , 'from' => $from, 'size' => $size
            ]
        ];
        $results = $this->client->search($params);
        return $results;
    }
    
    
    public function search_doc_fuzzy($keywords = "电脑",$from = 0,$size = 2) {
        $params = [
            'index' => self::INDEX_NAME,
            'body' => [
                'query' => [
                    'wildcard'=>[
                        'title'=>[
                            'value'=>$keywords.'*'
                        ]
                    ]
                ],
                'sort' => ['price'=>['order'=>'desc']]
                , 'from' => $from, 'size' => $size
            ]
        ];
        $results = $this->client->search($params);
        return $results;
    }
}

3,调用:

    public function create_index()
    {
        $es = new EsController();
        $r = $es->create_index();
        if($r['acknowledged'] === true){
            echo '索引创建成功';
        }
    }

    public function get_mapping()
    {
        $es = new EsController();
        $r = $es->get_mapping();
        var_dump($r);die;
    }

    public function delete_index()
    {
        $es = new EsController();
        $r = $es->delete_index();
        if($r['acknowledged'] === true){
            echo '索引删除成功';
        }
    }

    public function add_doc()
    {
        $docs = [];
        $docs[] = ['id'=>1,'title'=>'苹果手机','content'=>'苹果手机,很好很强大。','tags'=>'手机,小米','price'=>9999.99,'add_time'=>1634712429,'update_time'=>0];
        $docs[] = ['id'=>2,'title'=>'华为手环','content'=>'荣耀手环,你值得拥有。','tags'=>'手环,华为','price'=>300,99,'add_time'=>1634712429,'update_time'=>0];
        $docs[] = ['id'=>3,'title'=>'小度音响','content'=>'智能生活,快乐每一天。','tags'=>'音响,小度','price'=>100,'add_time'=>1634712429,'update_time'=>0];
        $docs[] = ['id'=>4,'title'=>'王者荣耀','content'=>'游戏就玩王者荣耀,快乐生活,很好很强大。','tags'=>'游戏','price'=>998,'add_time'=>1634712429,'update_time'=>0];
        $docs[] = ['id'=>5,'title'=>'小汪糕点','content'=>'糕点就吃小汪,好吃看得见。','tags'=>'糕点,食物','price'=>98,'add_time'=>1634712429,'update_time'=>0];
        $docs[] = ['id'=>6,'title'=>'小米手环3','content'=>'秒杀限量,快来。','tags'=>'手环,小米','price'=>998,99,'add_time'=>1634712429,'update_time'=>0];
        $docs[] = ['id'=>7,'title'=>'iPad','content'=>'iPad,不一样的电脑。','tags'=>'iPad,苹果','price'=>2998,99,'add_time'=>1634712429,'update_time'=>0];
        $docs[] = ['id'=>8,'title'=>'中华人民共和国','content'=>'中华人民共和国,伟大的国家。','tags'=>'中华人民共和国,国家','price'=>19999,'add_time'=>1634712429,'update_time'=>0];
        $es = new EsController();
        foreach ($docs as &$value){
            $es->add_doc($value['id'],$value);
        }
    }

    public function exists_doc()
    {
        $es = new EsController();
        $r = $es->exists_doc(8);
        if($r){
            echo  '文档存在';
        }
    }

    public function get_doc()
    {
        // 注:如果文档不存在,会抛出Missing404Exception异常,建议先查询文档是否存在,再获取文档
        $es = new EsController();
        $r = $es->get_doc(2);
        var_dump($r);
    }

    public function update_doc()
    {
        $es = new EsController();
        $doc = ['id'=>1,'title'=>'苹果手机222','content'=>'苹果手机,很好很强大。','tags'=>'手机,苹果','price'=>9999.99,'add_time'=>1634712429,'update_time'=>1634712429];
        $r = $es->update_doc(1,$doc);
        var_dump($r);
    }

    public function delete_doc()
    {
        $es = new EsController();
        $r = $es->delete_doc(8);
        var_dump($r);
    }

    public function search_doc()
    {
        $es = new EsController();
        $r = $es->search_doc('手机',0,3);
        var_dump($r);
    }

    public function search_doc_fuzzy()
    {
        $es = new EsController();
        $r = $es->search_doc_fuzzy('手',0,3);
        var_dump($r);
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4007387.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-22
下一篇 2022-10-22

发表评论

登录后才能评论

评论列表(0条)

保存