Thinkphp6.0使用elasticsearch


先通過composer安裝elasticsearch

composer require elasticsearch/elasticsearch

示例代碼:

<?php
namespace app\controller;
use app\BaseController;
use Elasticsearch\ClientBuilder;
use think\App;
use think\facade\Db;
class Index extends BaseController
{
    use TestTrait,TestTrait2;
    private $client;
    private $index_name;
    private $type;
    // 構造函數
    public function __construct(App $app)
    {
        parent::__construct($app);
        $params = array(
            '127.0.0.1:9200'
        );
        $this->client = ClientBuilder::create()->setHosts($params)->build();
    }
   /**設置索引跟 類型
     * @param string $index_name
     * @param string $type
     */
    public function set($index_name='index',$type='type'){
        $this->index_name=$index_name;
        $this->type=$type;
    }

     /**mysql涉及到搜索的數據插入文檔
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function sync(){
        $list=Db::name("test")->select();
        foreach ($list as $k => $v) {
            $r = $this->add_doc($v['id'],$v);
        }
    }
    // 搜索
   public function index(){
        //設置索引跟類型
        $this->set('ccc','bbb');
        //創建索引
        //  $this->create_index();
        //創建文檔結構
        $r=$this->create_mappings();
        //獲取文檔結構,查看映射
        $r=$this->get_mapping();
        $this->sync();
        //刪除索引
        //$this->delete_index();
        $id=1;
        //文檔是否存在
        $r=$this->exists_doc($id);
        if($r===true){
            //獲取文檔信息
            $r= $this->get_doc($id);
            //修改文檔
            $r=$this->update_doc($id,'name','小明3');
            //刪除文檔
           //   $this->delete_doc($id);
        }
        $r = $this->search_doc("刪庫 別煩我");
     //   dd($r);
    }
    // 刪除索引
    public function delete_index()
    {
        $params = ['index' => $this->index_name];
        return $this->client->indices()->delete($params);
    }
    // 創建索引

    /**
     * @return array|callable
     */
    public function create_index()
    {
        // 只能創建一次
        $params = [
            'index' => $this->index_name,
            'type' => $this->type,
            'body'=>[]
        ];
       return $this->client->index($params);


    }
    //獲取文檔
    public function get_doc($id){
        $params = [
            'index' =>$this->index_name,
            'type' => $this->type,
            'id'=>$id
        ];
        return  $this->client->get($params);
    }
    // 創建文檔模板
    public function create_mappings() {

        $params = [
            'index' => $this->index_name,
            'type' => $this->type,
            'include_type_name' => true,//7.0以上版本必須有
            'body' => [
                    'properties' => [
                        'id' => [
                            'type' => 'long', // 整型
                        ],
                        'name' => [
                            //5.x以上已經沒有string類型。如果需要分詞的話使用text,不需要分詞使用keyword。
                            'type' => 'text', // 字符串型
                        ],
                        'profile' => [
                            'type' => 'text',
                        ],
                        'age' => [
                            'type' => 'long',
                        ],
                        'job' => [
                            'type' => 'text',
                        ],
                    ]
  ]
        ];

        return $this->client->indices()->putMapping($params);
    }
    // 查看映射
    public function get_mapping() {
        $params = [
            'index' => $this->index_name,
            'type' => $this->type,
            'include_type_name' => true,//7.0以上版本必須有
        ];
        return $this->client->indices()->getMapping($params);
    }

   /**添加文檔
     * @param string $id
     * @param array $doc 跟創建文檔結構時properties的字段一致
     * @return array|callable
     */
    public function add_doc(string $id,array $doc) {
        $params = [
            'index' => $this->index_name,
            'type' => $this->type,
            'id' => $id,
            'body' => $doc
        ];
        return $this->client->index($params);
    }

    // 判斷文檔存在
    public function exists_doc($id = 1) {
        $params = [
            'index' => $this->index_name,
            'type' => $this->type,
            'id' => $id
        ];
        return $this->client->exists($params);
    }

    /**更新文檔
     * @param $id
     * @param $key
     * @param $value
     * @return array|callable
     */
    public function update_doc($id,$key,$value) {
        // 可以靈活添加新字段,最好不要亂添加
        $params = [
            'index' => $this->index_name,
            'type' => $this->type,
            'id' => $id,
            'body' => [
                'doc' => [
                    $key => $value
                ]
            ]
        ];

        return $this->client->update($params);
    }

    /**刪除文檔
     * @param int $id
     * @return array|callable
     */
    public function delete_doc($id = 1) {
        $params = [
            'index' => $this->index_name,
            'type' => $this->type,
            'id' => $id
        ];
        return $this->client->delete($params);
    }

    /**查詢表達式搜索
     * @param $keywords
     * @param $from
     * @param $size
     * @return array
     */
    public function search_doc1($keywords,$from,$size){
        return [
            'query' =>[
                          "match"=>[
                                //"name"=>$keywords, 或者
                                  "name"=>[
                                      'query' => $keywords,
                                      'boost' => 3, // 權重
                                  ],
                         ],
            ]
            ,
                    'from' => $from,
                    'size' => $size
               ];
    }

    /**短語搜索
     * @param $keywords
     * @param $from
     * @param $size
     * @return array
     */
    public function search_doc3($keywords,$from,$size){
        return [
            'query' =>[
                "match_phrase"=>[
                    //"name"=>$keywords, 或者
                    "name"=>[
                        'query' => $keywords,
                        'boost' => 3, // 權重
                    ],
                ],


            ]
            ,
            'from' => $from,
            'size' => $size
        ];
    }

    /**高亮搜索
     * @param string $keywords
     * @param $from
     * @param $size
     * @return array
     */
    public function search_doc4(string $keywords,$from,$size):array {
        return [
            'query' =>[
                "match_phrase"=>[
                    //"name"=>$keywords, 或者
                    "name"=>[
                        'query' => $keywords,
                        'boost' => 3, // 權重
                    ],
                ],
            ],
            'highlight'=>[
                "fields"=>[
                    //必須加object,要不然轉json時,這里依然是數組,而不是對象
                    "name"=>(object)[]
                ]
            ],
            'from' => $from,
            'size' => $size
        ];
    }

    /**搜索結果增加分析
     * @param string $keywords
     * @param int $from
     * @param int $size
     * @return array
     */
    public function search_doc5(string $keywords,int $from,int $size){
        return [
            'query' =>[
                'bool' => [
                    //必須匹配
                    "must"=>[
                        "match"=>[
                            "profile"=>$keywords,
                        ]
                    ],
                    //應該匹配
                    'should' => [
                        [ 'match' => [
                            'profile' => [
                                'query' => $keywords,
                                'boost' => 3, // 權重
                            ]]],
                        [ 'match' => [ 'name' => [
                            'query' => $keywords,
                            'boost' => 2,
                        ]]],
                    ],
                    //復雜的搜索 限制年齡大於25歲
                    'filter'=>[
                        "range"=>[
                            "age"=>["gt"=>25]
                        ]
                    ]
                ],
            ],
            'highlight'=>[
                "fields"=>[
                    //必須加object,要不然轉json時,這里依然是數組,而不是對象
                    "name"=>(object)[]
                ]
            ],
            'aggs'=>[
                "result"=>[
                    //terms 桶 統計文檔數量
                    "terms"=>[
                        "field"=>"age"
                    ]
                ],
                "avg"=>[
                    //avg 平均值
                    "avg"=>[
                        "field"=>"age"
                    ]
                ],
                "max"=>[
                    //max 最大值
                    "max"=>[
                        "field"=>"age"
                    ]
                ],
                "min"=>[
                    //avg 最小值
                    "min"=>[
                        "field"=>"age"
                    ]
                ],
            ],
            'from' => $from,
            'size' => $size,
        ];
    }

    /**使用過濾器 filter
     * @param $keywords
     * @param $from
     * @param $size
     * @return array
     */
    public function search_doc2($keywords,$from,$size){
        return  ['query' => [
                    'bool' => [
                        //必須匹配
                        "must"=>[
                            "match"=>[
                                "name"=>$keywords,
                            ]
                        ],
                        //應該匹配
                        'should' => [
                            [ 'match' => [
                                'profile' => [
                                        'query' => $keywords,
                                        'boost' => 3, // 權重
                            ]]],
                            [ 'match' => [ 'name' => [
                                'query' => $keywords,
                                'boost' => 2,
                            ]]],
                        ],
                        //復雜的搜索 限制年齡大於25歲
                        'filter'=>[
                            "range"=>[
                                "age"=>["gt"=>25]
                            ]
                        ]
                    ],

            ],
            //  'sort' => ['age'=>['order'=>'desc']],
            'from' => $from,
            'size' => $size
        ];
    }

    /** 查詢文檔 (分頁,排序,權重,過濾)
     * @param $keywords
     * @param int $from
     * @param int $size
     * @return array|callable
     */
    public function search_doc($keywords,$from = 0,$size = 12) {
        $query=$this->search_doc5($keywords,$from,$size);
        $params = [
            'index' => $this->index_name,
            'type' => $this->type,
            'body' => $query
        ];

        return $this->client->search($params);
    }

}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM