php-elasticsearch 使用(1)

安装

1,在composer.json 文件中引入 elasticsearch-php:

{

      "require":{

               "elasticsearch/elasticsearch":"~6.0"

       }

}

2,用composer客户端

curl -s http://getcomposer.org/install | php

php composer.phar install --no-dev

3,在项目中引入自动加载文件(如果还没引入),并且实例化一个客户端

require 'vendor/autoload.php';

use Elasticsearch\ClientBuilder;

$client = ClientBuilder::create()->build();

4,索引一个文档

在elasticsearch-php中,几乎一切操作都是用关联数组来配置。REST路径(endpoint),文档和可选参数都是用关联数组来配置

为了索引一个文档,我们要指定4部分信息:index , type , id 和一个body。构建一个键值对的关联数组就可以完成上面的内容。body的键值对格式与文档的数据保持一致性。

$data = $request->all();
$es_arr['index'] = "my_index";
$es_arr['type'] = "my_type";
$es_arr['id'] = "my_id";
$es_arr['body'] = ['name'=>"lisi","sex"=>'男',"age"=>22,"works"=>"IT"];

$client = ClientBuilder::create()->build();
$is_es = $client->index($client);
5,获取一个文档
$es_arr['index'] = "my_index";
$es_arr['type'] = "my_type";
$es_arr['id'] = "my_id";

$client = ClientBuilder::create()->build();
$es = $client->get($es_array);
响应数据包含一些元数据(如index、type等)和_source属性,这是你发送给Elasticsearch的原始文档数据
Array
(
[_index] => my_index
[_type] => my_type
[_id] => my_id
[_version] => 3
[found] => 1
[_source] => Array
(
[name] => lisi
[sex] => 男
[age] => 22
[works] => IT
)

)
6,搜索一个文档
搜索是elasticsearch的一个特色,所以我们试一下执行一个搜索。我们准备用Match查询:
$es_data["index"] = "my_index";
$es_data['type'] = "my_type";
$es_data['body']=[
"query"=>[
"match"=>[
'name'=>'lisi'
]
]
];
$client = ClientBuilder::create()->build();
$es = $client->search($es_data);
这个响应数据与前面例子的响应数据有所不同,这里有一些元数据(如took、time_out等)和一个hits的数组,这代表了你的搜索结果。而hits内部也有一个hits数组,内部hits包含特定的搜索结果:
Array
(
    [took] => 16 [timed_out] => [_shards] => Array ( [total] => 5 [successful] => 5 [skipped] => 0 [failed] => 0 ) [hits] => Array ( [total] => 1 [max_score] => 0.2876821 [hits] => Array ( [0] => Array ( [_index] => my_index [_type] => my_type [_id] => my_id [_score] => 0.2876821 [_source] => Array ( [testField] => abc ) ) ) ) )
7,删除一个文档
$es_data["index"] = "my_index";
$es_data['type'] = "my_type";
$es_data['id'] = "my_id";
$client = ClientBuilder::create()->build();
$es = $client->delete($es_data);
删除文档的语法和获取文档的语法是一样的。唯一不同的是delete方法替代了get方法。
8,删除一个索引
由于elasticsearch的动态特性,我们创建的第一个文档会自动创建一个索引,同时也会把settings里面的参数设定为默认参数。
$es_data['index'] = "my_index";
$client = ClientBuilder::create()->build();
$es = $client->indices()->delete($es_data);
9,创建一个索引
添加一个索引,同时要进行自定义settings:
$es_data['index'] = "my_index";
$es_data['body']=[
"settings"=>[
"number_of_shards"=>2,
"number_of_replicas"=>0
]
];
$client = ClientBuilder::create()->build();
$es = $client->indices()->create($es_data);
本节结语:
$client对象下的所有核心方法(索引,搜索,获取等)都是可用的。索引管理和集群管理分别在$client->indices()和$client->cluster()中。

猜你喜欢

转载自www.cnblogs.com/shangfz/p/11528320.html