安装与快速入门
安装
基本要求:
Elasticsearch版本要求:
Elasticsearch Version
Elasticsearch-PHP Branch(php api分支)
>= 5.0
5.0
>= 1.0, ⇐ 5.0
1.0, 2.0
⇐ 0.90.*
0.4
composer方式安装:
创建composer.json文件,加入以下内容.如果你的项目已经存在,加入相应的行即可.
{
"require": {
"elasticsearch/elasticsearch": "~5.0"
}
}使用composer安装elasticsearch-php库,
curl -s http://getcomposer.org/installer | php
php composer.phar install --no-dev如果您的项目已经存在则运行:php composer.phar update即可.
ok,elasticsearch-php库已经安装完毕
快速开始
实例化一个client
require 'vendor/autoload.php';
use Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()->build();在elasticsearch-php中,几乎所有的配置都是关联数组的方式.
索引一个文档
索引一个文档,需要指定四条信息:index, type, id 和 document body体.
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 'my_id',
'body' => ['testField' => 'abc']
];
$response = $client->index($params);
print_r($response);返回的相应,就是创建成功的文档和索引的相关信息,是一个关联数组的形式,其实是Elasticsearch返回的JSON版本后的数组解析
Array
(
[_index] => my_index
[_type] => my_type
[_id] => my_id
[_version] => 1
[created] => 1
)获取一个文档
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 'my_id'
];
$response = $client->get($params);
print_r($response);响应包含一些metadata(元数据)(index, type,等)以及_source字段…这是你送到Elasticsearch的原始文档。
Array
(
[_index] => my_index
[_type] => my_type
[_id] => my_id
[_version] => 1
[found] => 1
[_source] => Array
(
[testField] => abc
)
)搜索一个文档
使用Match query进行查询
$params = [
'index' => 'my_index',
'type' => 'my_type',
'body' => [
'query' => [
'match' => [
'testField' => 'abc'
]
]
]
];
$response = $client->search($params);
print_r($response);有点不同于以前的响应。我们看到一些元数据(took,timed_out等)和一个数组命名hits。这是你的搜索结果。
Array
(
[took] => 1
[timed_out] =>
[_shards] => Array
(
[total] => 5
[successful] => 5
[failed] => 0
)
[hits] => Array
(
[total] => 1
[max_score] => 0.30685282
[hits] => Array
(
[0] => Array
(
[_index] => my_index
[_type] => my_type
[_id] => my_id
[_score] => 0.30685282
[_source] => Array
(
[testField] => abc
)
)
)
)
)删除一个文档
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 'my_id'
];
$response = $client->delete($params);
print_r($response);删除后的相应:
Array
(
[found] => 1
[_index] => my_index
[_type] => my_type
[_id] => my_id
[_version] => 2
)删除一个索引
由于elasticsearch的动态特性,我们自动添加的第一个文档后默认会建立索引。
$deleteParams = [
'index' => 'my_index'
];
$response = $client->indices()->delete($deleteParams);
print_r($response);response:
Array
(
[acknowledged] => 1
)创建一个索引
$params = [
'index' => 'my_index',
'body' => [
'settings' => [
'number_of_shards' => 2,
'number_of_replicas' => 0
]
]
];
$response = $client->indices()->create($params);
print_r($response);Elasticsearch将根据你的设置创建索引,并返回一个确认:
Array
(
[acknowledged] => 1
)Last updated
Was this helpful?