https://blog.csdn.net/raoxiaoya/article/details/90602565
前言
Elasticsearch-PHP是PHP連接Elasticsearch庫的擴展,是用PHP語言開發的,類似於PHP通過Predis操作redis庫的功能。如果想詳細了解Elasticsearch的話,可以下載《Elasticsearch權威指南(中文版).pdf》。
下載安裝Elasticsearch-PHP
下載Elasticsearch-PHP的話。你可以直接去GitHub上下載,也可以通過Composer包管理工具直接下載。這里我是通過Composer包管理工具直接下載,所以此時我們需要安裝Composer,其實很簡單的,可以參考composer詳細安裝教程。
安裝好Composer之后就可以進行Elasticsearch-PHP的下載了。
首先我們在服務器根目錄下創建一個elasticphp文件夾,在該文件夾中創建一個composer.json文件,內容如下:
{
"require": {
"elasticsearch/elasticsearch": "2.2.1"
}
}
然后啟動Windows命令窗口cmd,進入到elasticphp目錄下,運行:composer update 命令。如下圖所示:
在這個下載過程中可能需要等待一段時間,下載完后再elasticphp目錄下會出現vender目錄文件,如下圖所示:
接下來我們可以在elasticphp目錄下創建一個index.php文件,內容如下:
require 'vendor/autoload.php'; //加載自動加載文件
#如果沒有設置主機地址默認為127.0.0.1:9200
$client = Elasticsearch\ClientBuilder::create()->setHosts(['localhost:9200'])->build();
var_dump($client);
如果出現如下圖所示,表示連接Elasticsearch服務成功,也即Elasticsearch-PHP安裝成功:
PHP通過Elasticsearch-PHP操作Elasticsearch庫
PHP使用Elasticsearch-PHP的要求:
PHP的版本在5.3以上,我的版本是PHP5.5。
在php.ini中開啟curl和openssl擴展
一、通過設置mapping結構創建一個索引庫(相當於mysql創建一個數據庫)
require 'vendor/autoload.php'; //加載自動加載文件
#如果沒有設置主機地址默認為127.0.0.1:9200
$client = Elasticsearch\ClientBuilder::create()->setHosts(['localhost:9200'])->build();
/**
* 創建庫索引的mapping結構
*/
$params = [
'index' => 'my_index', //索引名(相當於mysql的數據庫)
'body' => [
'settings' => [
'number_of_shards' => 5, #分片數
],
'mappings' => [
'my_type' => [ //類型名(相當於mysql的表)
'_all' => [
'enabled' => 'false'
],
'_routing' => [
'required' => 'true'
],
'properties' => [ //文檔類型設置(相當於mysql的數據類型)
'name' => [
'type' => 'string',
'store' => 'true'
],
'age' => [
'type' => 'integer'
]
]
]
]
]
];
$res = $client->indices()->create($params); //創建庫索引
二、庫索引操作
require 'vendor/autoload.php'; //加載自動加載文件
#如果沒有設置主機地址默認為127.0.0.1:9200
$client = Elasticsearch\ClientBuilder::create()->setHosts(['localhost:9200'])->build();
/**
* 庫索引操作
*/
$params = [
'index' => 'my_index-0',
'client' => [
'ignore' => 404
]
];
$res = $client->indices()->delete($params); //刪除庫索引
$res = $client->indices()->getSettings($params);//獲取庫索引設置信息
$res = $client->indices()->exists($params); //檢測庫是否存在
$res = $client->indices()->getMapping($params); //獲取mapping信息
三、文檔操作
/**
* 獲取指定文檔
*/
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => '3416a75f4cea9109507cacd8e2f2aefc'
];
$res = $client->get($params); //獲取指定的文檔
$res = $client->getSource($params); //獲取指定文檔的sourse內容(即字段的信息)
//刪除指定的文檔
$res = $client->delete($params);
/**
* 更新指定文檔
*/
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => '3416a75f4cea9109507cacd8e2f2aefc',
'body' => [
'doc' => [
'age' => 150
]
]
];
$res = $client->update($params);
/**
* 文檔查詢
*/
$params = [
'index' => 'my_index', //['my_index1', 'my_index2'],可以通過這種形式進行跨庫查詢
'type' => 'my_type',//['my_type1', 'my_type2'],
'body' => [
'query' => [
'match' => [
'age' => '24'
]
],
'from' => '0',
'size' => '200'
'sort' => [
'age' => 'desc' //對age字段進行降序排序
]
]
];
原文鏈接:https://blog.csdn.net/u014236259/article/details/53817022