php+elasticsearch查询

PHP技术
426
0
0
2022-11-16
标签   Elasticsearch

最近有些地方用到了搜索,但是搜索速度不达意所以使用es搜索,因此给自己做个标记,再这里做个记号,以后方便使用,以 windows 系统为例

1.华为开源镜像去下载es服务组件 :传送门:mirrors.huaweicloud.com/

php+elasticsearch查询

2.下载es类

composer require 'elasticsearch/elasticsearch'

3.下载java JDK,具体下载地址也能再上面的华为开源镜像中下载,因为很方便的老铁们,注意es版本对应相应的jdk

序号    Elasticsearch版本    JDK版本
1    Elasticsearch 5.0.x    OpenJDK/AdoptOpenJDK 8
2    Elasticsearch 5.1.x    OpenJDK/AdoptOpenJDK 8
3    Elasticsearch 5.2.x    OpenJDK/AdoptOpenJDK 8
4    Elasticsearch 5.3.x    OpenJDK/AdoptOpenJDK 8
5    Elasticsearch 5.4.x    OpenJDK/AdoptOpenJDK 8
6    Elasticsearch 5.5.x    OpenJDK/AdoptOpenJDK 8
7    Elasticsearch 5.6.x    OpenJDK/AdoptOpenJDK 8
8    Elasticsearch 6.0.x    OpenJDK/AdoptOpenJDK 8
9    Elasticsearch 6.1.x    OpenJDK/AdoptOpenJDK 8
10    Elasticsearch 6.2.x    OpenJDK/AdoptOpenJDK 8、OpenJDK 9
11    Elasticsearch 6.3.x    OpenJDK/AdoptOpenJDK 8、OpenJDK 10
12    Elasticsearch 6.4.x    OpenJDK/AdoptOpenJDK 8、OpenJDK 10
13    Elasticsearch 6.5.x    OpenJDK/AdoptOpenJDK 8、OpenJDK 11
14    Elasticsearch 6.6.x    OpenJDK/AdoptOpenJDK 8、OpenJDK 11
15    Elasticsearch 6.7.x    OpenJDK/AdoptOpenJDK 8、OpenJDK 11、OpenJDK 12
16    Elasticsearch 6.8.x    OpenJDK/AdoptOpenJDK 8、OpenJDK/AdoptOpenJDK 11、OpenJDK 12、OpenJDK/AdoptOpenJDK 13、OpenJDK/AdoptOpenJDK 14
17    Elasticsearch 7.0.x    OpenJDK/AdoptOpenJDK 8、OpenJDK 11、OpenJDK 12
18    Elasticsearch 7.1.x    OpenJDK/AdoptOpenJDK 8、OpenJDK 11、OpenJDK 12
19    Elasticsearch 7.2.x    OpenJDK/AdoptOpenJDK 8、OpenJDK 11、OpenJDK 12
20    Elasticsearch 7.3.x    OpenJDK/AdoptOpenJDK 8、OpenJDK 11、OpenJDK 12
21    Elasticsearch 7.4.x    OpenJDK/AdoptOpenJDK 8、OpenJDK/AdoptOpenJDK 11、OpenJDK/AdoptOpenJDK 13
22    Elasticsearch 7.5.x    OpenJDK/AdoptOpenJDK 8、OpenJDK/AdoptOpenJDK 11、OpenJDK/AdoptOpenJDK 13
23    Elasticsearch 7.6.x    OpenJDK/AdoptOpenJDK 8、OpenJDK/AdoptOpenJDK 11、OpenJDK/AdoptOpenJDK 13
24    Elasticsearch 7.7.x    OpenJDK/AdoptOpenJDK 8、OpenJDK/AdoptOpenJDK 11、OpenJDK/AdoptOpenJDK 14
25    Elasticsearch 7.8.x    OpenJDK/AdoptOpenJDK 8、OpenJDK/AdoptOpenJDK 11、OpenJDK/AdoptOpenJDK 14
26    Elasticsearch 7.9.x    OpenJDK/AdoptOpenJDK 8、OpenJDK/AdoptOpenJDK 11、OpenJDK/AdoptOpenJDK 14
27    Elasticsearch 7.10.x    OpenJDK/AdoptOpenJDK 8、OpenJDK/AdoptOpenJDK 11、OpenJDK/AdoptOpenJDK 14
28    Elasticsearch 7.11.x    OpenJDK/AdoptOpenJDK 8、OpenJDK/AdoptOpenJDK 11、OpenJDK/AdoptOpenJDK 15
29    Elasticsearch 7.12.x    OpenJDK/AdoptOpenJDK 8、OpenJDK/AdoptOpenJDK 11、OpenJDK/AdoptOpenJDK 15、OpenJDK/AdoptOpenJDK 16
30    Elasticsearch 7.13.x    OpenJDK/AdoptOpenJDK 8、OpenJDK/AdoptOpenJDK 11、OpenJDK/AdoptOpenJDK 16

4.启动es服务

两种方式:

  • 进入es安装目录使用命令启动 bin\elasticsearch
  • 或者直接进入bin文件双击 elasticsearch.bat 启动

php+elasticsearch查询

php+elasticsearch查询

要是看到这个页面就启动成功了

5.浏览器查看 访问:localhost:9200/ 看到一下页面,恭喜你安装成功了。

php+elasticsearch查询

6.创建ES类

<?php

namespace App\Http\Controllers\Api\Faninfo;



use Illuminate\Http\Request;
use App\Http\Controllers\Api\BaseController;
use Exception;

class EstestController extends BaseController
{

/**
 * es搜索demo
 * @param $request
 * 
 */ 
    private $client;
    const INDEX_NAME = 'test';      //  索引名称

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

    /**
     * @desc 创建索引和映射,只能创建一次
     * @return array|mixed|string
     */ 
    public function create_index() {

    try {    

        $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',   // 时间戳
                        ]
                    ]
                ]
            ]
        ];
            return $this->client->indices()->create($params);

        } catch (Exception $e) {
            $msg = $e->getMessage();
            $msg = json_decode($msg,true);
            return $msg;
        }
    }

    /**
     * @desc  删除索引
     * @return array
     */ 
    public function delete_index() {
        $params = ['index' => self::INDEX_NAME];
        $response = $this->client->indices()->delete($params);
        return $response;
    }


    /**
     * @desc 查看映射
     * @return array
     */ 
    public function get_mapping() {
        $params = [
            'index' => self::INDEX_NAME,
        ];
        $response = $this->client->indices()->getMapping($params);
        return $response;
    }

    /**
     * @desc 添加文档
     * @param $id
     * @param $doc
     * @return array
     */ 
    public function add_doc($id,$doc) {
        $params = [
            'index' => self::INDEX_NAME,
            'id' => $id,
            'body' => $doc
        ];
        $response = $this->client->index($params);
        return $response;
    }

    /**
     * @desc  判断文档是否存在
     * @param int $id
     * @return bool
     */ 
    public function exists_doc($id = 1) {
        $params = [
            'index' => self::INDEX_NAME,
            'id' => $id
        ];
        $response = $this->client->exists($params);
        return $response;
    }

    /**
     * @desc 获取文档
     * @param int $id
     * @return array
     */ 
    public function get_doc($id = 1) {
        $params = [
            'index' => self::INDEX_NAME,
            'id' => $id
        ];
        $response = $this->client->get($params);
        return $response;
    }

    /**
     * @desc  更新文档
     * @param int $id
     * @param $doc
     * @return array
     */ 
    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;
    }

    /**
     * @desc  删除文档
     * @param int $id
     * @return array
     */ 
    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,
                // 高亮显示 
                'highlight'=>[
                    "pre_tags" => ['<b style="color: red">'],
                    "post_tags" => ['</b>'],
                    'fields'=>[
                        'title'=>(object)[],
                        'content'=>(object)[]
                    ]
                ]
            ]
        ];
        $results = $this->client->search($params);
        return $results;
    }

    /**
     * @desc  模糊查询,查询 title 包含的关键词
     * @param string $keywords
     * @param int $from
     * @param int $size
     * @return array
     */ 
    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;
    }





}




7. 调用ES类

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

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

    public function delete_index()
    {
        $es = new EstestController();
        $r = $es->delete_index();
        if(isset($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 EstestController();
        foreach ($docs as &$value){
            $es->add_doc($value['id'],$value);
        }
    }

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

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

    public function update_doc()
    {
        $es = new EstestController();
        $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 EstestController();
        $r = $es->delete_doc(8);
        var_dump($r);
    }

    /**
     * @request 搜索关键词
     */ 
    public function search_doc(Request $request)
    {   $key = $request->key;
        $es = new EstestController();
        $r = $es->search_doc($key,0,3);
        // $r = $es->search_doc('手机',0,3); 
        var_dump($r);
    }

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