1. 程式人生 > 程式設計 >php操作ElasticSearch搜尋引擎流程詳解

php操作ElasticSearch搜尋引擎流程詳解

目錄
  • 一、安裝
  • 二、使用
  • 三、新建ES
  • 四、建立表
  • 五、插入資料
  • 六、 查詢所有資料
  • 七、查詢單條資料
  • 八、搜尋
  • 九、測試程式碼

〝 古人學問遺無力,少壯功夫老始成 〞

如果這篇文章能給你帶來一點幫助,希望給飛兔小哥哥一鍵三連,表示支援,謝謝各位小夥伴們。

一、安裝

通過composer安裝

composer require 'elasticsearch/elasticsearch'

二、使用

建立ES類

<?
 
require 'vendor/autoload.php';
 
//如果未設定密碼
$es = \Elasticsearch\ClientBuilder::create()->setHosts(['xxx.xxx.xxx.xxx'])->build();
 
//如果es設定了密碼
$es = \Elasticsearch\ClientBuilder::create()->setHosts(['http://username:[email protected]:9200'])->build()

三、新建ES資料庫

index 對應關係型資料(以下簡稱)裡面的資料庫,而不是對應MySQL裡面的索引

<?php
$params = [
    'index' => 'autofelix_db',#index的名字不能是大寫和下劃線開頭
    'body' => [
        'settings' => [
            'number_of_shards' => 5,'number_of_replicas' => 0
        ]
    ]
];
$es->indices()->create($params);

四、建立表

  • 在MySQL裡面,光有了資料庫還不行,還需要建立表,ES也是一樣的
  • ES中的type對應MySQL裡面的表
  • ES6以前,一個index有多個type,就像MySQL中一個數據庫有多個表一樣
  • 但是ES6以後,每個index只允許一個type
  • 在定義欄位的時候,可以看出每個欄位可以定義單獨的型別
  • 在first_name中還自定義了 分詞器 ik,這是個外掛,是需要單獨安裝的
<?php
$params = [
    'index' => 'autofelix_db','type' => 'autofelix_table','body' => [
        'mytype' => [
            '_source' => [
                'enabled' => true
            ],'properties' => [
                'id' => [
                    'type' => 'integer'
                ],'first_name' => [
                    'type' => 'text','analyzer' => 'ik_max_word'
                ],'last_name' => [
                    'type' => 'text','age' => [
                    'type' => 'integer'
                ]
            ]
        ]
    ]
];
$es->indices()->putMapping($params);

五、插入資料

  • 現在資料庫和表都有了,可以往裡面插入資料了
  • 在ES裡面的資料叫文件
  • 可以多插入一些資料,等會可以模擬搜尋功能
<?php
$params = [
    'index' => 'autofelix_db',//'id' => 1,#可以手動指定id,也可以不指定隨機生成
    'body' => [
        'first_name' => '飛','last_name' => '兔','age' => 26
    ]
];
$es->index($params);

六、 查詢所有資料

<?php
$data = $es->search();
 
var_dump($data);

七、查詢單條資料

  • 如果你在插入資料的時候指定了id,就可以查詢的時候加上id
  • 如果你在插入的時候未指定id,系統將會自動生成id,你可以通過查詢所有資料後檢視其id
<?php
$params = [
    'index' => 'autofelix_db','id' =>  //你插入資料時候的id
];
$data = $es->get($params);

八、搜尋

ES精髓的地方就在於搜尋

<?php
$params = [
    'index' => 'autofelix_db','body' => [
        'query' => [
            'constant_score' => [ //非評分模式執行
                'filter' => [ //過濾器,不會計算相關度,速度快
                    'term' => [ //精確查詢,不支援多個條件
                        'first_name' => '飛'
                    ]
                ]
            ]
        ]
    ]
];
 
$data = $es->search($params);
var_dump($data);

九、測試程式碼

基於Laravel環境,包含刪除資料庫,刪除文件等操作

<?php
use Elasticsearch\ClientBuilder;
use Faker\Generator as Faker;
 
/**
 * ES 的 php 實測程式碼
 */
class EsDemo
{
    private $EsClient = null;
    private $faker = null;
 
    /**
     * 為了簡化測試,本測試預設只操作一個Index,一個Type
     */
    private $index = 'autofelix_db';
    private $type = 'autofelix_table';
 
    public function __construct(Faker $faker)
    {
        /**
         * 例項化 ES 客戶端
         */
        $this->EsClient = ClientBuilder::create()->setHosts(['xxx.xxx.xxx.xxx'])->build();
        /**
         * 這是一個數據生成庫
         */
        $this->faker = $faker;
    }
 
    /**
     * 批量生成文件
     * @param $num
     */
    public function generateDoc($num = 100) {
        foreach (range(1,$num) as $item) {
            $this->putDoc([
                'first_name' => $this->faker->name,'last_name' => $this->faker->name,'age' => $this->faker->numberBetween(20,80)
            ]);
        }
    }
 
    /**
     * 刪除一個文件
     * @param $id
     * @return array
     */
    public function delDoc($id) {
        $params = [
            'index' => $this->index,'type' => $this->type,'id' =>$id
        ];
        return $this->EsClient->delete($params);
    }
 
    /**
     * 搜尋文件,query是查詢條件
     * @param array $query
     * @param int $from
     * @param int $size
     * @return array
     */
    public function search($query = [],$from = 0,$size = 5) {
//        $query = [
//            'query' => [
//                'bool' => [
//                    'must' => [
//                        'match' => [
//                            'first_name' => 'Cronin',//                        ]
//                    ],//                    'filter' => [
//                        'range' => [
//                            'age' => ['gt' => 76]
//                        ]
//                    ]
//                ]
//
//            ]
//        ];
        $params = [
            'index' => $this->index,//            'index' => 'm*',#index 和 type 是可以模糊匹配的,甚至這兩個引數都是可選的
            'type' => $this->type,'_source' => ['first_name','age'],// 請求指定的欄位
            'body' => array_merge([
                'from' => $from,'size' => $size
 www.cppcns.com           ],$query)
        ];
        return $this->EsClient->search($params);
    }
 
    /**
     * 一次獲取多個文件
     * @param $ids
    vFcxnCJ * @return array
     */
    public function getDocs($ids) {
        $params = [
            'index' => $this->index,'body' => ['ids' => $ids]
        ];
        return $this->EsClient->mget($params);
    }
 
    /**
     * 獲取單個文件
     * @param $id
     * @return array
     */
    public function getDoc($id) {
        $params = [
            'index' => $this->index,'id' =>$id
        ];
        return $this->EsClient->get($params);
    }
 
    /**
     * 更新一個文件
     * @param $id
     * @return array
     */
    public function updateDoc($id) {
        $params = [
            'index' => $this->index,'id' =>$id,'body' => [
                'doc' => [
                    'first_name' => '張','last_name' => '三','age' => 99
                ]
            ]
        ];
        return $this->EsClient->update($params);
    }
 
    /**
     * 新增一個文件到 Index 的Type中
     * @param array $body
     * @return void
     */
    public function putDoc($body = []) {
        $params = [
            'index' => $this->index,// 'id' => 1,#可以手動指定id,也可以不指定隨機生成
            'body' => $body
        ];
        $this->EsClient->index($params);
    }
 
    /**
     * 刪除所有的 Index
     */
    public function delAllIndex() {
        $indexList = $this->esStatus()['indices'];
        foreach ($indexList as $item => $index) {
            $this->delIndex();
        }
    }
 
    /**
     * 獲取 ES 的狀態資訊,包括index 列表
     * @return array
     */
    public function esStatus() {
        return $this->EsClient->indices()->stats();
    }
 
    /**
     * 建立一個索引 Index (非關係型資料庫裡面那個索引,而是關係型資料裡面的資料庫的意思)
     * @return void
     */
    public function createIndex() {
        $this->delIndex();
        $params = [
            'index' => $this->index,'body' => [
                'settings' => [
                    'number_of_shards' => 2,'number_of_replicas' => 0
                ]
            ]
        ];
        $this->EsClient->indices()->create($params);
    }
 
    /**
     * 檢查Index 是否存在
     * @return bool
     */
    public function checkIndexExists() {
        $params = [
            'index' => $this->index
        ];
        return $this->EsClient->indices()->exists($params);
    }
 
    /**
     * 刪除一個Index
     * @return void
     */
    public function delIndex() {
        $params = [
            'index' => $this->index
        ];
        if ($this->checkIndexExists()) {
            $this->EsClient->indices()->delete($params);
        }
    }
 
    /**
     * 獲取Index的文件模板資訊
     * @return array
     */
    public function getMapping() {
        $params = [
            'index' => $this->index
        ];
        return $this->EsClient->客棧;indices()->getMapping($params);
    }
 
    /**
     * 建立文件模板
     * @return void
     */
    public function createMapping() {
        $this->createIndex();
        $params = [
            'index' => $this->index,'body' => [
                $this->type => [
                    '_source' => [
                        'enabled' => true
                    ],'properties' => [
                        'id' => [
                            'type' => 'integer'
                        ],'first_name' => [
                            'type' => 'text','analyzer' => 'ik_max_word'
                        ],'last_name' => [
                            'type' => 'text','age' => [
                            'type' => 'integer'
                        ]
                    ]
                ]
            ]
        ];
        $this->EsClient->indices()->putMapping($params);
        $this->generateDoc();
    }
}

到此這篇關於php操作ElasticSearch搜尋引擎流程詳解的文章就介紹到這了,更多相關php ElasticSearch搜尋引擎內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!