PHP thinkphp6.0使用elasticsearch

PHP版elasticsearch的GitHub地址
通過(guò)composer安裝

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;
    // 構(gòu)造函數(shù)
    public function __construct(App $app)
    {
        parent::__construct($app);
        $params = array(
            '127.0.0.1:9200'
        );
        $this->client = ClientBuilder::create()->setHosts($params)->build();
    }
   /**設(shè)置索引跟 類型
     * @param string $index_name
     * @param string $type
     */
    public function set($index_name='index',$type='type'){
        $this->index_name=$index_name;
        $this->type=$type;
    }

     /**mysql涉及到搜索的數(shù)據(jù)插入文檔
     * @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(){
        //設(shè)置索引跟類型
        $this->set('ccc','bbb');
        //創(chuàng)建索引
        //  $this->create_index();
        //創(chuàng)建文檔結(jié)構(gòu)
        $r=$this->create_mappings();
        //獲取文檔結(jié)構(gòu)壳嚎,查看映射
        $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("刪庫(kù) 別煩我");
     //   dd($r);
    }
    // 刪除索引
    public function delete_index()
    {
        $params = ['index' => $this->index_name];
        return $this->client->indices()->delete($params);
    }
    // 創(chuàng)建索引

    /**
     * @return array|callable
     */
    public function create_index()
    {
        // 只能創(chuàng)建一次
        $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);
    }
    // 創(chuàng)建文檔模板
    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以上已經(jīng)沒有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 跟創(chuàng)建文檔結(jié)構(gòu)時(shí)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);
    }

    /**查詢表達(dá)式搜索
     * @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, // 權(quán)重
                                  ],
                         ],
            ]
            ,
                    'from' => $from,
                    'size' => $size
               ];
    }

    /**短語(yǔ)搜索
     * @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, // 權(quán)重
                    ],
                ],


            ]
            ,
            '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, // 權(quán)重
                    ],
                ],
            ],
            'highlight'=>[
                "fields"=>[
                    //必須加object,要不然轉(zhuǎn)json時(shí),這里依然是數(shù)組箩溃,而不是對(duì)象
                    "name"=>(object)[]
                ]
            ],
            'from' => $from,
            'size' => $size
        ];
    }

    /**搜索結(jié)果增加分析
     * @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,
                        ]
                    ],
                    //應(yīng)該匹配
                    'should' => [
                        [ 'match' => [
                            'profile' => [
                                'query' => $keywords,
                                'boost' => 3, // 權(quán)重
                            ]]],
                        [ 'match' => [ 'name' => [
                            'query' => $keywords,
                            'boost' => 2,
                        ]]],
                    ],
                    //復(fù)雜的搜索 限制年齡大于25歲
                    'filter'=>[
                        "range"=>[
                            "age"=>["gt"=>25]
                        ]
                    ]
                ],
            ],
            'highlight'=>[
                "fields"=>[
                    //必須加object,要不然轉(zhuǎn)json時(shí)碌嘀,這里依然是數(shù)組涣旨,而不是對(duì)象
                    "name"=>(object)[]
                ]
            ],
            'aggs'=>[
                "result"=>[
                    //terms 桶 統(tǒng)計(jì)文檔數(shù)量
                    "terms"=>[
                        "field"=>"age"
                    ]
                ],
                "avg"=>[
                    //avg 平均值
                    "avg"=>[
                        "field"=>"age"
                    ]
                ],
                "max"=>[
                    //max 最大值
                    "max"=>[
                        "field"=>"age"
                    ]
                ],
                "min"=>[
                    //avg 最小值
                    "min"=>[
                        "field"=>"age"
                    ]
                ],
            ],
            'from' => $from,
            'size' => $size,
        ];
    }

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

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

    /** 查詢文檔 (分頁(yè),排序股冗,權(quán)重霹陡,過(guò)濾)
     * @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);
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市止状,隨后出現(xiàn)的幾起案子烹棉,更是在濱河造成了極大的恐慌,老刑警劉巖怯疤,帶你破解...
    沈念sama閱讀 219,366評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件浆洗,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡集峦,警方通過(guò)查閱死者的電腦和手機(jī)伏社,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)塔淤,“玉大人摘昌,你說(shuō)我怎么就攤上這事「叻洌” “怎么了聪黎?”我有些...
    開封第一講書人閱讀 165,689評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)妨马。 經(jīng)常有香客問(wèn)我挺举,道長(zhǎng)杀赢,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,925評(píng)論 1 295
  • 正文 為了忘掉前任湘纵,我火速辦了婚禮脂崔,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘梧喷。我一直安慰自己砌左,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,942評(píng)論 6 392
  • 文/花漫 我一把揭開白布铺敌。 她就那樣靜靜地躺著汇歹,像睡著了一般。 火紅的嫁衣襯著肌膚如雪偿凭。 梳的紋絲不亂的頭發(fā)上产弹,一...
    開封第一講書人閱讀 51,727評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音弯囊,去河邊找鬼痰哨。 笑死,一個(gè)胖子當(dāng)著我的面吹牛匾嘱,可吹牛的內(nèi)容都是我干的斤斧。 我是一名探鬼主播,決...
    沈念sama閱讀 40,447評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼霎烙,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼撬讽!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起悬垃,我...
    開封第一講書人閱讀 39,349評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤游昼,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后盗忱,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體酱床,經(jīng)...
    沈念sama閱讀 45,820評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,990評(píng)論 3 337
  • 正文 我和宋清朗相戀三年趟佃,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了扇谣。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,127評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡闲昭,死狀恐怖罐寨,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情序矩,我是刑警寧澤鸯绿,帶...
    沈念sama閱讀 35,812評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響瓶蝴,放射性物質(zhì)發(fā)生泄漏毒返。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,471評(píng)論 3 331
  • 文/蒙蒙 一舷手、第九天 我趴在偏房一處隱蔽的房頂上張望拧簸。 院中可真熱鬧,春花似錦男窟、人聲如沸盆赤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)牺六。三九已至,卻和暖如春汗捡,著一層夾襖步出監(jiān)牢的瞬間淑际,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工凉唐, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留庸追,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,388評(píng)論 3 373
  • 正文 我出身青樓台囱,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親读整。 傳聞我的和親對(duì)象是個(gè)殘疾皇子簿训,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,066評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容