0%

Elasticsearch(2)PHP驱动

安装完成composer之后。我们需要安装php的类库来对Elasticsearch进行连接。

我们现在需要使用的是elasticsearch/elasticsearch

比如我们的项目目录在 /data/project/elastic

我们就可以在这个目录下执行以下命令:

1
composer require elasticsearch/elasticsearch

如果出现如下内容:

1
Using version ^5.0 for elasticsearch/elasticsearch
2
./composer.json has been updated
3
Loading composer repositories with package information
4
Updating dependencies (including require-dev)
5
Package operations: 5 installs, 0 updates, 0 removals
6
  - Installing react/promise (v2.5.0) Downloading: 100%         
7
  - Installing guzzlehttp/streams (3.0.0) Downloading: 100%         
8
  - Installing guzzlehttp/ringphp (1.1.0) Downloading: 100%         
9
  - Installing psr/log (1.0.2) Downloading: 100%         
10
  - Installing elasticsearch/elasticsearch (v5.0.0) Downloading: 100%         
11
elasticsearch/elasticsearch suggests installing monolog/monolog (Allows for client-level logging and tracing)
12
Writing lock file
13
Generating autoload files

就表示已经安装成功了。

接下来我们编辑如下文件。

1
<?php
2
require_once './vendor/autoload.php';
3
4
$client = Elasticsearch\ClientBuilder::create();
5
$client->setHosts(['127.0.0.1']);
6
$client = $client->build();
7
$info = $client->info();
8
var_dump($info);
9
?>

然后保存为index.php。我们可以通过访问该文件来确认是否请求成功了。

然后我们执行一下:

1
[root@68 elastic]# php index.php 
2
array(5) {
3
  ["name"]=>
4
  string(7) "ZQZ38Da"
5
  ["cluster_name"]=>
6
  string(13) "elasticsearch"
7
  ["cluster_uuid"]=>
8
  string(22) "FuPCyv2ZSimGYxAo_nLvpw"
9
  ["version"]=>
10
  array(5) {
11
    ["number"]=>
12
    string(5) "5.1.1"
13
    ["build_hash"]=>
14
    string(7) "5395e21"
15
    ["build_date"]=>
16
    string(24) "2016-12-06T12:36:15.409Z"
17
    ["build_snapshot"]=>
18
    bool(false)
19
    ["lucene_version"]=>
20
    string(5) "6.3.0"
21
  }
22
  ["tagline"]=>
23
  string(20) "You Know, for Search"
24
}

这样就表示我们的驱动已经安装并且连接完成了。

具体的文档我们可点击:https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html