elasticsearch-php ================= [![Build status](https://github.com/elastic/elasticsearch-php/workflows/PHP%20test/badge.svg)](https://github.com/elastic/elasticsearch-php/actions) [![Latest Stable Version](https://poser.pugx.org/elasticsearch/elasticsearch/v/stable)](https://packagist.org/packages/elasticsearch/elasticsearch) [![Total Downloads](https://poser.pugx.org/elasticsearch/elasticsearch/downloads)](https://packagist.org/packages/elasticsearch/elasticsearch) Official 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. To 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. Starting from version `7.4.0`, all the endpoints (and namespaces) are autogenerated using the [util/GenerateEndpoints.php](https://github.com/elastic/elasticsearch-php/blob/master/util/GenerateEndpoints.php) script. This script reads the [Elasticsearch API specs](https://github.com/elastic/elasticsearch/tree/master/rest-api-spec/src/main/resources/rest-api-spec/api) and generated the PHP classes for all the endpoints. Starting from version `7.7.0` we included also the [XPack endpoints](https://www.elastic.co/what-is/open-x-pack) of Elasticsearch. These APIs are related to: - [Cross-cluster replication](https://www.elastic.co/guide/en/elasticsearch/reference/current/ccr-apis.html) - [Graph explorer](https://www.elastic.co/guide/en/elasticsearch/reference/current/graph-explore-api.html) - [Info](https://www.elastic.co/guide/en/elasticsearch/reference/current/info-api.html) - [Licensing](https://www.elastic.co/guide/en/elasticsearch/reference/current/licensing-apis.html) - [Machine learning anomaly detection](https://www.elastic.co/guide/en/elasticsearch/reference/current/ml-apis.html) - [Machine learning data frame analytics](https://www.elastic.co/guide/en/elasticsearch/reference/current/ml-df-analytics-apis.html) - [Migration](https://www.elastic.co/guide/en/elasticsearch/reference/current/migration-api.html) - [Reload search analyzers](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-reload-analyzers.html) - [Rollup](https://www.elastic.co/guide/en/elasticsearch/reference/current/rollup-apis.html) - [Security](https://www.elastic.co/guide/en/elasticsearch/reference/current/security-api.html) - [Snapshot lifecycle management](https://www.elastic.co/guide/en/elasticsearch/reference/current/snapshot-lifecycle-management-api.html) - [Transform](https://www.elastic.co/guide/en/elasticsearch/reference/current/transform-apis.html) - [Usage](https://www.elastic.co/guide/en/elasticsearch/reference/current/usage-api.html) - [Watcher](https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api.html) Table of Contents ================= - [elasticsearch-php](#elasticsearch-php) * [Features](#features) * [Version Matrix](#version-matrix) * [Compatibility](#compatibility) * [Documentation](#documentation) * [Installation via Composer](#installation-via-composer) * [PHP Version Requirement](#php-version-requirement) * [Quickstart](#quickstart) + [Index a document](#index-a-document) + [Get a document](#get-a-document) + [Search for a document](#search-for-a-document) + [Delete a document](#delete-a-document) + [Delete an index](#delete-an-index) + [Create an index](#create-an-index) - [Unit Testing using Mock a Elastic Client](#unit-testing-using-mock-a-elastic-client) - [Contributing](#contributing) - [Wrap up](#wrap-up) * [Available Licenses](#available-licenses) + [Contributions](#contributions) Features -------- - One-to-one mapping with REST API and other language clients - Configurable, automatic discovery of cluster nodes - Persistent, Keep-Alive connections (within the lifetime of the script) - Load balancing (with pluggable selection strategy) across all available nodes. Defaults to round-robin - Pluggable connection pools to offer different connection strategies - Generalized, pluggable architecture - most components can be replaced with your own custom class if specialized behavior is required - Option to use asynchronous future, which enables parallel execution of curl requests to multiple nodes **Note:** [X-Pack](https://www.elastic.co/what-is/open-x-pack) endpoints are included from elasticsearch-php 7.7+. Version Matrix -------------- | Elasticsearch-PHP Branch | PHP Version | | ----------- | ------------------------ | | >= 7.16.0, < 8.0.0 | >= 7.3.0, <= 8.1.99 | | >= 7.12.0, < 8.0.0 | >= 7.3.0, <= 8.0.99 | | >= 7.11.0, < 8.0.0 | >= 7.1.0, <= 8.0.99 | | >= 7.0.0, < 7.11.0 | >= 7.1.0, < 8.0.0 | | 6.x | >= 7.0.0, < 8.0.0 | | 5.x | >= 5.6.6, < 8.0.0 | | 2.x | >= 5.4.0, < 7.0.0 | | 0.4, 1.x | >= 5.3.9, < 7.0.0 | - If you are using Elasticsearch 7.x, you can use Elasticsearch-PHP 7.x branch. - If you are using Elasticsearch 6.x, you can use Elasticsearch-PHP 6.x branch. - If you are using Elasticsearch 5.x, you can use Elasticsearch-PHP 6.x branch. - 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. - 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. - 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. Compatibility ------------- Language clients are forward compatible; meaning that clients support communicating with greater minor versions of Elasticsearch. Elastic language clients are also backwards compatible with lesser supported minor Elasticsearch versions. Documentation -------------- [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! We also provide a code examples generator for PHP using the `util/GenerateDocExamples.php` script. This command parses the `util/alternative_report.spec.json` file produced from this [JSON specification](https://raw.githubusercontent.com/elastic/built-docs/master/raw/en/elasticsearch/reference/master/alternatives_report.json) and it generates the PHP examples for each digest value. The examples are stored in asciidoc format under `docs/examples` folder. Installation via Composer ------------------------- The recommended method to install _Elasticsearch-PHP_ is through [Composer](http://getcomposer.org). 1. 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): ```json { "require": { "elasticsearch/elasticsearch": "^7.0" } } ``` 2. Download and install Composer: ```bash curl -s http://getcomposer.org/installer | php ``` 3. Install your dependencies: ```bash php composer.phar install ``` 4. Require Composer's autoloader 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: ```php build(); ``` You can find out more on how to install Composer, configure autoloading, and other best-practices for defining dependencies at [getcomposer.org](http://getcomposer.org). PHP Version Requirement ---- Version 7.0 of this library requires at least PHP version 7.1. In addition, it requires the native JSON extension to be version 1.3.7 or higher. | Elasticsearch-PHP Branch | PHP Version | | ----------- | ------------------------ | | 7.0 | >= 7.1.0 | | 6.0 | >= 7.0.0 | | 5.0 | >= 5.6.6 | | 2.0 | >= 5.4.0 | | 0.4, 1.0 | >= 5.3.9 | Quickstart ---- ### Index a document In elasticsearch-php, almost everything is configured by associative arrays. The REST endpoint, document and optional parameters - everything is an associative array. To index a document, we need to specify three pieces of information: index, id and a document body. This is done by constructing an associative array of key:value pairs. The request body is itself an associative array with key:value pairs corresponding to the data in your document: ```php $params = [ 'index' => 'my_index', 'id' => 'my_id', 'body' => ['testField' => 'abc'] ]; $response = $client->index($params); print_r($response); ``` The response that you get back indicates the document was created in the index that you specified. The response is an associative array containing a decoded version of the JSON that Elasticsearch returns: ```php Array ( [_index] => my_index [_type] => _doc [_id] => my_id [_version] => 1 [result] => created [_shards] => Array ( [total] => 1 [successful] => 1 [failed] => 0 ) [_seq_no] => 0 [_primary_term] => 1 ) ``` ### Get a document Let's get the document that we just indexed. This will simply return the document: ```php $params = [ 'index' => 'my_index', 'id' => 'my_id' ]; $response = $client->get($params); print_r($response); ``` The response contains some metadata (index, version, etc.) as well as a `_source` field, which is the original document that you sent to Elasticsearch. ```php Array ( [_index] => my_index [_type] => _doc [_id] => my_id [_version] => 1 [_seq_no] => 0 [_primary_term] => 1 [found] => 1 [_source] => Array ( [testField] => abc ) ) ``` If you want to retrieve the `_source` field directly, there is the `getSource` method: ```php $params = [ 'index' => 'my_index', 'id' => 'my_id' ]; $source = $client->getSource($params); print_r($source); ``` The response will be just the `_source` value: ```php Array ( [testField] => abc ) ``` ### Search for a document Searching is a hallmark of Elasticsearch, so let's perform a search. We are going to use the Match query as a demonstration: ```php $params = [ 'index' => 'my_index', 'body' => [ 'query' => [ 'match' => [ 'testField' => 'abc' ] ] ] ]; $response = $client->search($params); print_r($response); ``` The response is a little different from the previous responses. We see some metadata (`took`, `timed_out`, etc.) and an array named `hits`. This represents your search results. Inside of `hits` is another array named `hits`, which contains individual search results: ```php Array ( [took] => 33 [timed_out] => [_shards] => Array ( [total] => 1 [successful] => 1 [skipped] => 0 [failed] => 0 ) [hits] => Array ( [total] => Array ( [value] => 1 [relation] => eq ) [max_score] => 0.2876821 [hits] => Array ( [0] => Array ( [_index] => my_index [_type] => _doc [_id] => my_id [_score] => 0.2876821 [_source] => Array ( [testField] => abc ) ) ) ) ) ``` ### Delete a document Alright, let's go ahead and delete the document that we added previously: ```php $params = [ 'index' => 'my_index', 'id' => 'my_id' ]; $response = $client->delete($params); print_r($response); ``` You'll notice this is identical syntax to the `get` syntax. The only difference is the operation: `delete` instead of `get`. The response will confirm the document was deleted: ```php Array ( [_index] => my_index [_type] => _doc [_id] => my_id [_version] => 2 [result] => deleted [_shards] => Array ( [total] => 1 [successful] => 1 [failed] => 0 ) [_seq_no] => 1 [_primary_term] => 1 ) ``` ### Delete an index Due 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: ```php $deleteParams = [ 'index' => 'my_index' ]; $response = $client->indices()->delete($deleteParams); print_r($response); ``` The response: ```php Array ( [acknowledged] => 1 ) ``` ### Create an index Now that we are starting fresh (no data or index), let's add a new index with some custom settings: ```php $params = [ 'index' => 'my_index', 'body' => [ 'settings' => [ 'number_of_shards' => 2, 'number_of_replicas' => 0 ] ] ]; $response = $client->indices()->create($params); print_r($response); ``` Elasticsearch will now create that index with your chosen settings, and return an acknowledgement: ```php Array ( [acknowledged] => 1 ) ``` Unit Testing using Mock a Elastic Client ======================================== ```php use GuzzleHttp\Ring\Client\MockHandler; use Elasticsearch\ClientBuilder; // The connection class requires 'body' to be a file stream handle // Depending on what kind of request you do, you may need to set more values here $handler = new MockHandler([ 'status' => 200, 'transfer_stats' => [ 'total_time' => 100 ], 'body' => fopen('somefile.json'), 'effective_url' => 'localhost' ]); $builder = ClientBuilder::create(); $builder->setHosts(['somehost']); $builder->setHandler($handler); $client = $builder->build(); // Do a request and you'll get back the 'body' response above ``` Contributing ============ If you want to contribute to this project you need to subscribe to a [Contributor Agreement](https://www.elastic.co/contributor-agreement). If you want to send a PR for version `Y` please use the `Y.x` branch. For instance if you want to send a PR for **elasticsearch-php 7** use the `7.x` branch. Never send PR to `master` unless you want to contribute to the development version of the client (`master` represents the next major version). Each PR should include a **unit test** using [PHPUnit](https://phpunit.de/). If you are not familiar with PHPUnit you can have a look at this [reference](https://phpunit.readthedocs.io/en/7.0/). Wrap up ======= That 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. You'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. Check 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. Available Licenses ------- Starting with version 1.3.1, Elasticsearch-PHP is available under two licenses: Apache v2.0 and LGPL v2.1. Versions prior to 1.3.1 are still licensed with only Apache v2.0. The user may choose which license they wish to use. Since there is no discriminating executable or distribution bundle to differentiate licensing, the user should document their license choice externally, in case the library is re-distributed. If no explicit choice is made, assumption is that redistribution obeys rules of both licenses. ### Contributions All contributions to the library are to be so that they can be licensed under both licenses. Apache v2.0 License: >Copyright 2013-2016 Elasticsearch > >Licensed under the Apache License, Version 2.0 (the "License"); >you may not use this file except in compliance with the License. >You may obtain a copy of the License at > > http://www.apache.org/licenses/LICENSE-2.0 > >Unless required by applicable law or agreed to in writing, software >distributed under the License is distributed on an "AS IS" BASIS, >WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. >See the License for the specific language governing permissions and >limitations under the License. LGPL v2.1 Notice: >Copyright (C) 2013-2016 Elasticsearch > >This library is free software; you can redistribute it and/or >modify it under the terms of the GNU Lesser General Public >License as published by the Free Software Foundation; either >version 2.1 of the License, or (at your option) any later version. > >This library is distributed in the hope that it will be useful, >but WITHOUT ANY WARRANTY; without even the implied warranty of >MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU >Lesser General Public License for more details. > >You should have received a copy of the GNU Lesser General Public >License along with this library; if not, write to the Free Software >Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA