環境
php 7.2
elasticsearch 6.2 下載
elasticsearch-php 6 下載
安裝 elasticsearch 下載源文件,解壓,重新建一個用戶,將目錄的所屬組修改為此用戶,因為 elasticsearch 無法用 root 用戶啟動。 wget https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-6.2.3.tar.gz tar zxvf elasticsearch-6.2.3.tar.gz useradd elasticsearch password elasticsearch chown elasticsearch:elasticsearch elasticsearch-6.2.3 cd elasticsearch-6.2.3 ./bin/elasticsearch // 啟動
安裝 PHP 擴展
我這里使用的是 composer 安裝 elasticsearch-php。在 composer.json 文件中加入 "elasticsearch/elasticsearch": "~6.0",執行 composer update。
{ "require": { // ... "elasticsearch/elasticsearch": "~6.0" // ... } }
測試例子
創建表和測試數據
我這里准備了一張文章表來進行測試,首先是建表,其次寫入測試數據,准備工作完畢之后,就開始編輯測試用例
create table articles( id int not null primary key auto_increment, title varchar(200) not null comment '標題', content text comment '內容' ); insert into articles(title, content) values ('Laravel 測試1', 'Laravel 測試文章內容1'), ('Laravel 測試2', 'Laravel 測試文章內容2'), ('Laravel 測試3', 'Laravel 測試文章內容3');
從 Mysql 讀取數據
try { $db = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', 'root'); $sql = 'select * from articles'; $query = $db->prepare($sql); $query->execute(); $lists = $query->fetchAll(); print_r($lists); } catch (Exception $e) { echo $e->getMessage(); }
實例化
require './vendor/autoload.php'; use Elasticsearch\ClientBuilder; $client = ClientBuilder::create()->build();
名詞解釋:索引相當於 MySQL 中的表,文檔相當於 MySQL 中的行記錄
elasticsearch 的動態性質,在添加第一個文檔的時候自動創建了索引和一些默認設置。
具體使用方法例子:
/引入es搜索類 //require './vendor/autoload.php'; use Elasticsearch\ClientBuilder; class Index { public function index() { /*$client = ClientBuilder::create()->setHosts($hosts)->build();*/ //實例化es類;在項目中引入自動加載文件,並且實例化一個客戶端: $client = ClientBuilder::create()->build(); try { //將文檔加入索引 //echo ClientBuilder::$aaa; $data = db::name('articles')->select(); //查詢出多條數據添加索引 foreach ($data as $k => $v) { $params = [ 'index' => 'article_index', 'type' => 'article_type', 'id' => 'article_' . $v['id'], 'body' => [ 'id' => $v['id'], 'title' => $v['title'], 'content' => $v['content'], ], ]; $response = $client->index($params); } //從索引中獲取文檔 $getparams = [ 'index' => 'article_index', 'type' => 'article_type', 'id' => 'article_1' ]; $res = $client->get($getparams); //從索引中刪除文檔 $delparams = [ 'index' => 'article_index', 'type' => 'article_type', 'id' => 'article_1' ]; $res = $client->delete($delparams); //刪除索引 $params = [ 'index' => 'articles_index' ]; $res = $client->indices()->delete($params); print_r($res); //搜索 $serparams = [ 'index' => 'article_index', 'type' => 'article_type', ]; $serparams['body']['query']['match']['content'] = '文章內容6'; $resech = $client->search($serparams); pp($resech); // pp($data); } catch (Exception $e) { echo $e->getMessage(); } }
