1elasticsearch-php 2================= 3 4[](https://travis-ci.org/elastic/elasticsearch-php) [](https://packagist.org/packages/elasticsearch/elasticsearch) [](https://packagist.org/packages/elasticsearch/elasticsearch) 5 6 7Official low-level client for Elasticsearch. Its goal is to provide common ground for all Elasticsearch-related code in PHP; because of this it tries to be opinion-free and very extendable. 8 9To maintain consistency across all the low-level clients (Ruby, Python, etc.), clients accept simple associative arrays as parameters. All parameters, from the URI to the document body, are defined in the associative array. 10 11 12Features 13-------- 14 15 - One-to-one mapping with REST API and other language clients 16 - Configurable, automatic discovery of cluster nodes 17 - Persistent, Keep-Alive connections (within the lifetime of the script) 18 - Load balancing (with pluggable selection strategy) across all available nodes. Defaults to round-robin 19 - Pluggable connection pools to offer different connection strategies 20 - Generalized, pluggable architecture - most components can be replaced with your own custom class if specialized behavior is required 21 - Option to use asynchronous future, which enables parallel execution of curl requests to multiple nodes 22 23 24**Note:** If you want to use X-Pack API, you need to install an optional extension [elasticsearch/xpack](https://github.com/elastic/elasticsearch-x-pack-php). 25 26 27Version Matrix 28-------------- 29 30| Elasticsearch Version | Elasticsearch-PHP Branch | 31| --------------------- | ------------------------ | 32| >= 7.0, < 8.0 | 7.0 | 33| >= 6.6, < 7.0 | 6.7.x | 34| >= 6.0, < 6.6 | 6.5.x | 35| >= 5.0, < 6.0 | 5.0 | 36| >= 2.0, < 5.0 | 1.0 or 2.0 | 37| >= 1.0, < 2.0 | 1.0 or 2.0 | 38| <= 0.90.x | 0.4 | 39 40 - If you are using Elasticsearch 7.x, use Elasticsearch-PHP 7.0 branch. 41 - If you are using Elasticsearch 6.6 to 6.7, use Elasticsearch-PHP 6.7.x branch. 42 - If you are using Elasticsearch 6.0 to 6.5, use Elasticsearch-PHP 6.5.x branch. 43 - If you are using Elasticsearch 5.x, use Elasticsearch-PHP 5.0 branch. 44 - If you are using Elasticsearch 1.x or 2.x, prefer using the Elasticsearch-PHP 2.0 branch. The 1.0 branch is compatible however. 45 - If you are using a version older than 1.0, you must install the `0.4` Elasticsearch-PHP branch. Since ES 0.90.x and below is now EOL, the corresponding `0.4` branch will not receive any more development or bugfixes. Please upgrade. 46 - You should never use Elasticsearch-PHP Master branch, as it tracks Elasticsearch master and may contain incomplete features or breaks in backwards compatibility. Only use ES-PHP master if you are developing against ES master for some reason. 47 48Documentation 49-------------- 50[Full documentation can be found here.](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html) Docs are stored within the repo under /docs/, so if you see a typo or problem, please submit a PR to fix it! 51 52Installation via Composer 53------------------------- 54The recommended method to install _Elasticsearch-PHP_ is through [Composer](http://getcomposer.org). 55 561. Add `elasticsearch/elasticsearch` as a dependency in your project's `composer.json` file (change version to suit your version of Elasticsearch, for instance for ES 7.0): 57 58 ```json 59 { 60 "require": { 61 "elasticsearch/elasticsearch": "^7.0" 62 } 63 } 64 ``` 65 662. Download and install Composer: 67 68 ```bash 69 curl -s http://getcomposer.org/installer | php 70 ``` 71 723. Install your dependencies: 73 74 ```bash 75 php composer.phar install 76 ``` 77 784. Require Composer's autoloader 79 80 Composer also prepares an autoload file that's capable of autoloading all the classes in any of the libraries that it downloads. To use it, just add the following line to your code's bootstrap process: 81 82 ```php 83 <?php 84 85 use Elasticsearch\ClientBuilder; 86 87 require 'vendor/autoload.php'; 88 89 $client = ClientBuilder::create()->build(); 90 ``` 91 92You can find out more on how to install Composer, configure autoloading, and other best-practices for defining dependencies at [getcomposer.org](http://getcomposer.org). 93 94PHP Version Requirement 95---- 96Version 7.0 of this library requires at least PHP version 7.1. In addition, it requires the native JSON 97extension to be version 1.3.7 or higher. 98 99| Elasticsearch-PHP Branch | PHP Version | 100| ----------- | ------------------------ | 101| 7.0 | >= 7.1.0 | 102| 6.0 | >= 7.0.0 | 103| 5.0 | >= 5.6.6 | 104| 2.0 | >= 5.4.0 | 105| 0.4, 1.0 | >= 5.3.9 | 106 107 108Quickstart 109---- 110 111 112### Index a document 113 114In elasticsearch-php, almost everything is configured by associative arrays. The REST endpoint, document and optional parameters - everything is an associative array. 115 116To index a document, we need to specify three pieces of information: index, id and a document body. This is done by 117constructing an associative array of key:value pairs. The request body is itself an associative array with key:value pairs 118corresponding to the data in your document: 119 120```php 121$params = [ 122 'index' => 'my_index', 123 'id' => 'my_id', 124 'body' => ['testField' => 'abc'] 125]; 126 127$response = $client->index($params); 128print_r($response); 129``` 130 131The response that you get back indicates the document was created in the index that you specified. The response is an 132associative array containing a decoded version of the JSON that Elasticsearch returns: 133 134```php 135Array 136( 137 [_index] => my_index 138 [_type] => _doc 139 [_id] => my_id 140 [_version] => 1 141 [result] => created 142 [_shards] => Array 143 ( 144 [total] => 1 145 [successful] => 1 146 [failed] => 0 147 ) 148 149 [_seq_no] => 0 150 [_primary_term] => 1 151) 152``` 153 154### Get a document 155 156Let's get the document that we just indexed. This will simply return the document: 157 158```php 159$params = [ 160 'index' => 'my_index', 161 'id' => 'my_id' 162]; 163 164$response = $client->get($params); 165print_r($response); 166``` 167 168The response contains some metadata (index, version, etc.) as well as a `_source` field, which is the original document 169that you sent to Elasticsearch. 170 171```php 172Array 173( 174 [_index] => my_index 175 [_type] => _doc 176 [_id] => my_id 177 [_version] => 1 178 [_seq_no] => 0 179 [_primary_term] => 1 180 [found] => 1 181 [_source] => Array 182 ( 183 [testField] => abc 184 ) 185 186) 187``` 188 189If you want to retrieve the `_source` field directly, there is the `getSource` method: 190 191```php 192$params = [ 193 'index' => 'my_index', 194 'id' => 'my_id' 195]; 196 197$source = $client->getSource($params); 198print_r($source); 199``` 200 201The response will be just the `_source` value: 202 203```php 204Array 205( 206 [testField] => abc 207) 208``` 209 210### Search for a document 211 212Searching is a hallmark of Elasticsearch, so let's perform a search. We are going to use the Match query as a demonstration: 213 214```php 215$params = [ 216 'index' => 'my_index', 217 'body' => [ 218 'query' => [ 219 'match' => [ 220 'testField' => 'abc' 221 ] 222 ] 223 ] 224]; 225 226$response = $client->search($params); 227print_r($response); 228``` 229 230The response is a little different from the previous responses. We see some metadata (`took`, `timed_out`, etc.) and 231an array named `hits`. This represents your search results. Inside of `hits` is another array named `hits`, which contains 232individual search results: 233 234```php 235Array 236( 237 [took] => 33 238 [timed_out] => 239 [_shards] => Array 240 ( 241 [total] => 1 242 [successful] => 1 243 [skipped] => 0 244 [failed] => 0 245 ) 246 247 [hits] => Array 248 ( 249 [total] => Array 250 ( 251 [value] => 1 252 [relation] => eq 253 ) 254 255 [max_score] => 0.2876821 256 [hits] => Array 257 ( 258 [0] => Array 259 ( 260 [_index] => my_index 261 [_type] => _doc 262 [_id] => my_id 263 [_score] => 0.2876821 264 [_source] => Array 265 ( 266 [testField] => abc 267 ) 268 269 ) 270 271 ) 272 273 ) 274 275) 276``` 277 278### Delete a document 279 280Alright, let's go ahead and delete the document that we added previously: 281 282```php 283$params = [ 284 'index' => 'my_index', 285 'id' => 'my_id' 286]; 287 288$response = $client->delete($params); 289print_r($response); 290``` 291 292You'll notice this is identical syntax to the `get` syntax. The only difference is the operation: `delete` instead of 293`get`. The response will confirm the document was deleted: 294 295```php 296Array 297( 298 [_index] => my_index 299 [_type] => _doc 300 [_id] => my_id 301 [_version] => 2 302 [result] => deleted 303 [_shards] => Array 304 ( 305 [total] => 1 306 [successful] => 1 307 [failed] => 0 308 ) 309 310 [_seq_no] => 1 311 [_primary_term] => 1 312) 313``` 314 315 316### Delete an index 317 318Due to the dynamic nature of Elasticsearch, the first document we added automatically built an index with some default settings. Let's delete that index because we want to specify our own settings later: 319 320```php 321$deleteParams = [ 322 'index' => 'my_index' 323]; 324$response = $client->indices()->delete($deleteParams); 325print_r($response); 326``` 327 328The response: 329 330 331```php 332Array 333( 334 [acknowledged] => 1 335) 336``` 337 338### Create an index 339 340Now that we are starting fresh (no data or index), let's add a new index with some custom settings: 341 342```php 343$params = [ 344 'index' => 'my_index', 345 'body' => [ 346 'settings' => [ 347 'number_of_shards' => 2, 348 'number_of_replicas' => 0 349 ] 350 ] 351]; 352 353$response = $client->indices()->create($params); 354print_r($response); 355``` 356 357Elasticsearch will now create that index with your chosen settings, and return an acknowledgement: 358 359```php 360Array 361( 362 [acknowledged] => 1 363) 364``` 365 366Unit Testing using Mock a Elastic Client 367======================================== 368```php 369use GuzzleHttp\Ring\Client\MockHandler; 370use Elasticsearch\ClientBuilder; 371 372// The connection class requires 'body' to be a file stream handle 373// Depending on what kind of request you do, you may need to set more values here 374$handler = new MockHandler([ 375 'status' => 200, 376 'transfer_stats' => [ 377 'total_time' => 100 378 ], 379 'body' => fopen('somefile.json'), 380 'effective_url' => 'localhost' 381]); 382$builder = ClientBuilder::create(); 383$builder->setHosts(['somehost']); 384$builder->setHandler($handler); 385$client = $builder->build(); 386// Do a request and you'll get back the 'body' response above 387``` 388 389Wrap up 390======= 391 392That was just a crash-course overview of the client and its syntax. If you are familiar with Elasticsearch, you'll notice that the methods are named just like REST endpoints. 393 394You'll also notice that the client is configured in a manner that facilitates easy discovery via the IDE. All core actions are available under the `$client` object (indexing, searching, getting, etc.). Index and cluster management are located under the `$client->indices()` and `$client->cluster()` objects, respectively. 395 396Check out the rest of the [Documentation](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html) to see how the entire client works. 397 398 399Available Licenses 400------- 401 402Starting with version 1.3.1, Elasticsearch-PHP is available under two licenses: Apache v2.0 and LGPL v2.1. Versions 403prior to 1.3.1 are still licensed with only Apache v2.0. 404 405The user may choose which license they wish to use. Since there is no discriminating executable or distribution bundle 406to differentiate licensing, the user should document their license choice externally, in case the library is re-distributed. 407If no explicit choice is made, assumption is that redistribution obeys rules of both licenses. 408 409### Contributions 410All contributions to the library are to be so that they can be licensed under both licenses. 411 412Apache v2.0 License: 413>Copyright 2013-2016 Elasticsearch 414> 415>Licensed under the Apache License, Version 2.0 (the "License"); 416>you may not use this file except in compliance with the License. 417>You may obtain a copy of the License at 418> 419> http://www.apache.org/licenses/LICENSE-2.0 420> 421>Unless required by applicable law or agreed to in writing, software 422>distributed under the License is distributed on an "AS IS" BASIS, 423>WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 424>See the License for the specific language governing permissions and 425>limitations under the License. 426 427LGPL v2.1 Notice: 428>Copyright (C) 2013-2016 Elasticsearch 429> 430>This library is free software; you can redistribute it and/or 431>modify it under the terms of the GNU Lesser General Public 432>License as published by the Free Software Foundation; either 433>version 2.1 of the License, or (at your option) any later version. 434> 435>This library is distributed in the hope that it will be useful, 436>but WITHOUT ANY WARRANTY; without even the implied warranty of 437>MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 438>Lesser General Public License for more details. 439> 440>You should have received a copy of the GNU Lesser General Public 441>License along with this library; if not, write to the Free Software 442>Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 443