{"id":27158868,"url":"https://github.com/activecollab/elasticsearch-php","last_synced_at":"2025-07-04T00:05:41.286Z","repository":{"id":285226914,"uuid":"880283770","full_name":"activecollab/elasticsearch-php","owner":"activecollab","description":"Backup copy of ElasticSearch API client","archived":false,"fork":false,"pushed_at":"2024-10-29T13:05:01.000Z","size":554,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-10T06:04:39.428Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/activecollab.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-10-29T13:01:17.000Z","updated_at":"2024-10-29T13:05:06.000Z","dependencies_parsed_at":null,"dependency_job_id":"fcd6fb04-480f-4008-bb01-26569b3d267e","html_url":"https://github.com/activecollab/elasticsearch-php","commit_stats":null,"previous_names":["activecollab/elasticsearch-php"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/activecollab/elasticsearch-php","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/activecollab%2Felasticsearch-php","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/activecollab%2Felasticsearch-php/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/activecollab%2Felasticsearch-php/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/activecollab%2Felasticsearch-php/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/activecollab","download_url":"https://codeload.github.com/activecollab/elasticsearch-php/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/activecollab%2Felasticsearch-php/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263421921,"owners_count":23464048,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-04-08T22:39:14.124Z","updated_at":"2025-07-04T00:05:41.265Z","avatar_url":"https://github.com/activecollab.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cimg align=\"right\" width=\"auto\" height=\"auto\" src=\"https://www.elastic.co/static-res/images/elastic-logo-200.png\"/\u003e\n\nElasticsearch PHP client\n========================\n\n[![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)\n\nThis is the official PHP client for \n[Elasticsearch](https://www.elastic.co/elasticsearch/).\n\n## Contents\n\n- [Getting started](#getting-started-)\n- [Configuration](#configuration)\n  - [Use Elastic Cloud](#use-elastic-cloud)\n- [Usage](#usage)\n  - [Index a document](#index-a-document)\n  - [Search a document](#search-a-document)\n  - [Delete a document](#delete-a-document)\n- [Versioning](#versioning)\n- [Backward Incompatible Changes](#backward-incompatible-changes-)\n- [Mock the Elasticsearch client](#mock-the-elasticsearch-client)\n- [FAQ](#faq-)\n- [Contribute](#contribute-)\n- [License](#license-)\n\n***\n\n## Getting started 🐣\n\nUsing this client assumes that you have an \n[Elasticsearch](https://www.elastic.co/elasticsearch/) server installed and \nrunning.\n\nYou can install the client in your PHP project using \n[composer](https://getcomposer.org/):\n\n```bash\ncomposer require elasticsearch/elasticsearch\n```\n\nAfter the installation you can connect to Elasticsearch using the \n`ClientBuilder` class. For instance, if your Elasticsearch is running on \n`localhost:9200` you can use the following code:\n\n```php\n\nuse Elastic\\Elasticsearch\\ClientBuilder;\n\n$client = ClientBuilder::create()\n    -\u003esetHosts(['localhost:9200'])\n    -\u003ebuild();\n\n// Info API\n$response = $client-\u003einfo();\n\necho $response['version']['number']; // 8.0.0\n```\n\nThe `$response` is an object of `Elastic\\Elasticsearch\\Response\\Elasticsearch`\nclass that implements `ElasticsearchInterface`, PSR-7 \n[ResponseInterface](https://www.php-fig.org/psr/psr-7/#33-psrhttpmessageresponseinterface)\nand [ArrayAccess](https://www.php.net/manual/en/class.arrayaccess.php).\n\nThis means the `$response` is a [PSR-7](https://www.php-fig.org/psr/psr-7/)\nobject:\n\n```php\necho $response-\u003egetStatusCode(); // 200\necho (string) $response-\u003egetBody(); // Response body in JSON\n```\n\nand also an \"array\", meaning you can access the response body as an\nassociative array, as follows:\n\n\n```php\necho $response['version']['number']; // 8.0.0\n\nvar_dump($response-\u003easArray());  // response body content as array\n```\n\nMoreover, you can access the response body as object, string or bool:\n\n```php\necho $response-\u003eversion-\u003enumber; // 8.0.0\n\nvar_dump($response-\u003easObject()); // response body content as object\nvar_dump($response-\u003easString()); // response body as string (JSON)\nvar_dump($response-\u003easBool());   // true if HTTP response code between 200 and 300\n```\n\n## Configuration\n\nElasticsearch 8.0 offers \n[security by default](https://www.elastic.co/blog/introducing-simplified-elastic-stack-security),\nthat means it uses [TLS](https://en.wikipedia.org/wiki/Transport_Layer_Security)\nfor protect the communication between client and server.\n\nIn order to configure `elasticsearch-php` for connecting to Elasticsearch 8.0 we\nneed to have the certificate authority file (CA).\n\nYou can install Elasticsearch in different ways, for instance using \n[Docker](https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html)\nyou need to execute the followind command:\n\n```bash\ndocker pull docker.elastic.co/elasticsearch/elasticsearch:8.0.1\n```\nOnce you have the docker image installed, you can execute Elasticsearch, for \ninstance using a single-node cluster configuration, as follows:\n\n```bash\ndocker network create elastic\ndocker run --name es01 --net elastic -p 9200:9200 -p 9300:9300 -it docker.elastic.co/elasticsearch/elasticsearch:8.0.1\n```\n\nThis command creates an `elastic` Docker network and start Elasticsearch\nusing the port `9200` (default).\n\nWhen you run the docker imnage a password is generated for the `elastic` user\nand it's printed to the terminal (you might need to scroll back a bit in the \nterminal to view it). You have to copy it since we will need to connect to \nElasticsearch.\n\nNow that Elasticsearch is running we can get the `http_ca.crt` file certificate.\nWe need to copy it from the docker instance, using the following command:\n\n```bash\ndocker cp es01:/usr/share/elasticsearch/config/certs/http_ca.crt .\n```\n\nOnce we have the `http_ca.crt` certificate and the `password`, copied during the\nstart of Elasticsearch, we can use it to connect with `elasticsearch-php` as \nfollows:\n\n```php\n$client = ClientBuilder::create()\n    -\u003esetHosts(['https://localhost:9200'])\n    -\u003esetBasicAuthentication('elastic', 'password copied during Elasticsearch start')\n    -\u003esetCABundle('path/to/http_ca.crt')\n    -\u003ebuild();\n```\n\nFor more information about the Docker configuration of Elasticsearch you can\nread the official documentation \n[here](https://www.elastic.co/guide/en/elasticsearch/reference/current/docker.html).\n\n### Use Elastic Cloud\n\nYou can use [Elastic Cloud](https://www.elastic.co/cloud/) as server with \n`elasticsearch-php`. Elastic Cloud is the PaaS solution offered by \n[Elastic](https://www.elastic.co).\n\nFor connecting to Elastic Cloud you just need the `Cloud ID` and the `API key`.\n\nYou can get the `Cloud ID` from the `My deployment` page of your dashboard (see \nthe red rectangle reported in the screenshot).\n\n![Cloud ID](docs/images/cloud_id.png)\n\nYou can generate an `API key` in the `Management` page under the section \n`Security`.\n\n![Security](docs/images/create_api_key.png)\n\nWhen you click on `Create API key` button you can choose a name and set the \nother options (for example, restrict privileges, expire after time, and so on).\n\n![Choose an API name](docs/images/api_key_name.png)\n\nAfter this step you will get the `API key`in the API keys page. \n\n![API key](docs/images/cloud_api_key.png)\n\n**IMPORTANT**: you need to copy and store the `API key`in a secure place, since \nyou will not be able to view it again in Elastic Cloud.\n\nOnce you have collected the `Cloud ID` and the `API key`, you can use \n`elasticsearch-php` to connect to your Elastic Cloud instance, as follows:\n\n```php\n$client = ClientBuilder::create()\n    -\u003esetElasticCloudId('insert here the Cloud ID')\n    -\u003esetApiKey('insert here the API key')\n    -\u003ebuild();\n```\n\n## Usage\n\nThe `elasticsearch-php` client offers 400+ endpoints for interacting with \nElasticsearch. A list of all these endpoints is available in the \n[official documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/rest-apis.html)\nof Elasticsearch APIs.\n\nHere we reported the basic operation that you can perform with the client: \nindex, search and delete.\n\n### Index a document\n\nYou can store (index) a JSON document in Elasticsearch using the following code:\n\n```php\nuse Elastic\\Elasticsearch\\Exception\\ClientResponseException;\nuse Elastic\\Elasticsearch\\Exception\\ServerResponseException;\n\n$params = [\n    'index' =\u003e 'my_index',\n    'body'  =\u003e [ 'testField' =\u003e 'abc']\n];\n\ntry {\n  $response = $client-\u003eindex($params);\n} catch (ClientResponseException $e) {\n  // manage the 4xx error\n} catch (ServerResponseException $e) {\n  // manage the 5xx error\n} catch (Exception $e) {\n  // eg. network error like NoNodeAvailableException\n}\n\nprint_r($response-\u003easArray());  // response body content as array\n```\n\nElasticsearch stores the `{\"testField\":\"abc\"}` JSON document in the `my_index` \nindex. The `ID` of the document is created automatically by Elasticsearch and \nstored in `$response['_id']` field value. If you want to specify an `ID` for the \ndocument you need to store it in `$params['id']`.\n\nYou can manage errors using `ClientResponseException` and \n`ServerResponseException`. The PSR-7 response is available using \n`$e-\u003egetResponse()` and the HTTP status code is available using `$e-\u003egetCode()`.\n\n### Search a document\n\nElasticsearch provides many different way to search documents. The simplest \nsearch that you can perform is a \n[match query](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html),\nas follows:\n\n```php\n$params = [\n    'index' =\u003e 'my_index',\n    'body'  =\u003e [\n        'query' =\u003e [\n            'match' =\u003e [\n                'testField' =\u003e 'abc'\n            ]\n        ]\n    ]\n];\n$response = $client-\u003esearch($params);\n\nprintf(\"Total docs: %d\\n\", $response['hits']['total']['value']);\nprintf(\"Max score : %.4f\\n\", $response['hits']['max_score']);\nprintf(\"Took      : %d ms\\n\", $response['took']);\n\nprint_r($response['hits']['hits']); // documents\n```\n\nUsing Elasticsearch you can perform different query search, for more information \nwe suggest toread the official documention reported \n[here](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-your-data.html).\n\n### Delete a document\n\nYou can delete a document specifing the `index` name and the `ID` of the \ndocument, as follows:\n\n```php\nuse Elastic\\Elasticsearch\\Exception\\ClientResponseException;\n\ntry {\n    $response = $client-\u003edelete([\n        'index' =\u003e 'my_index',\n        'id' =\u003e 'my_id'\n    ]);\n} catch (ClientResponseException $e) {\n    if ($e-\u003egetCode() === 404) {\n        // the document does not exist\n    }\n}\nif ($response['acknowledge'] === 1) {\n    // the document has been delete\n}\n```\n\nFor more information about the Elasticsearch REST API you can read the official \ndocumentation [here](https://www.elastic.co/guide/en/elasticsearch/reference/current/rest-apis.html).\n\n### Versioning\n\nThis client is versioned and released alongside Elasticsearch server.\n\nTo guarantee compatibility, use the most recent version of this library within \nthe major version of the corresponding Enterprise Search implementation.\n\nFor example, for Elasticsearch `7.16`, use `7.16` of this library or above, but \nnot `8.0`.\n\n## Backward Incompatible Changes :boom:\n\nThe 8.0.0 version of `elasticsearch-php` contains a new implementation compared \nwith 7.x. It supports [PSR-7](https://www.php-fig.org/psr/psr-7/) for HTTP \nmessages and [PSR-18](https://www.php-fig.org/psr/psr-18/) for HTTP client \ncommunications. \n\nWe tried to reduce the BC breaks as much as possible with `7.x` but there are \nsome (big) differences:\n\n- we changed the namespace, now everything is under `Elastic\\Elasticsearch`\n- we used the \n  [elastic-transport-php](https://github.com/elastic/elastic-transport-php) \n  library for HTTP communications;\n- we changed the `Exception` model, using the namespace \n  `Elastic\\Elasticsearch\\Exception`. All the exceptions extends the \n  `ElasticsearchException` interface, as in 7.x\n- we changed the response type of each endpoints using an \n  [Elasticsearch](src/Response/Elasticsearch.php) response class. This class \n  wraps a a [PSR-7](https://www.php-fig.org/psr/psr-7/) response allowing the \n  access of the body response as array or object. This means you can access the \n  API response as in 7.x, no BC break here! :angel:\n- we changed the `ConnectionPool` in `NodePool`. The `connection` naming was \n  ambigous since the objects are nodes (hosts)\n\nYou can have a look at the [BREAKING_CHANGES](BREAKING_CHANGES.md) file for more \ninformation.\n\n## Mock the Elasticsearch client\n\nIf you need to mock the Elasticsearch client you just need to mock a\n[PSR-18](https://www.php-fig.org/psr/psr-18/) HTTP Client.\n\nFor instance, you can use the \n[php-http/mock-client](https://github.com/php-http/mock-client) as follows:\n\n```php\nuse Elastic\\Elasticsearch\\ClientBuilder;\nuse Elastic\\Elasticsearch\\Response\\Elasticsearch;\nuse Http\\Mock\\Client;\nuse Nyholm\\Psr7\\Response;\n\n$mock = new Client(); // This is the mock client\n\n$client = ClientBuilder::create()\n    -\u003esetHttpClient($mock)\n    -\u003ebuild();\n\n// This is a PSR-7 response\n$response = new Response(\n    200, \n    [Elasticsearch::HEADER_CHECK =\u003e Elasticsearch::PRODUCT_NAME],\n    'This is the body!'\n);\n$mock-\u003eaddResponse($response);\n\n$result = $client-\u003einfo(); // Just calling an Elasticsearch endpoint\n\necho $result-\u003easString(); // This is the body!\n```\n\nWe are using the `ClientBuilder::setHttpClient()` to set the mock client.\nYou can specify the response that you want to have using the \n`addResponse($response)` function. As you can see the `$response` is a PSR-7 \nresponse object. In this example we used the `Nyholm\\Psr7\\Response` object from \nthe [nyholm/psr7](https://github.com/Nyholm/psr7) project. If you are using \n[PHPUnit](https://phpunit.de/) you can even mock the `ResponseInterface` as \nfollows:\n\n```php\n$response = $this-\u003ecreateMock('Psr\\Http\\Message\\ResponseInterface');\n```\n\n**Notice**: we added a special header in the HTTP response. This is the product \ncheck header, and it is required for guarantee that `elasticsearch-php` is \ncommunicating with an Elasticsearch server 8.0+.\n\nFor more information you can read the \n[Mock client](https://docs.php-http.org/en/latest/clients/mock-client.html) \nsection of PHP-HTTP documentation.\n\n## FAQ 🔮\n\n### Where do I report issues with the client?\n\nIf something is not working as expected, please open an \n[issue](https://github.com/elastic/elasticsearh-php/issues/new).\n\n### Where else can I go to get help?\n\nYou can checkout the \n[Elastic community discuss forums](https://discuss.elastic.co/).\n\n## Contribute 🚀\n\nWe welcome contributors to the project. Before you begin, some useful info...\n\n+ If you want to contribute to this project you need to subscribe to a \n  [Contributor Agreement](https://www.elastic.co/contributor-agreement).\n+ Before opening a pull request, please create an issue to \n  [discuss the scope of your proposal](https://github.com/elastic/elasticsearch-php/issues).\n+ If you want to send a PR for version `8.0` please use the `8.0` branch, for \n  `8.1` use the `8.1` branch and so on. \n+ Never send PR to `master` unless you want to contribute to the development \n  version of the client (`master` represents the next major version).\n+ Each PR should include a **unit test** using [PHPUnit](https://phpunit.de/). \n  If you are not familiar with PHPUnit you can have a look at the \n  [reference](https://phpunit.readthedocs.io/en/9.5/). \n\nThanks in advance for your contribution! :heart:\n\n## License 📗\n\n[MIT](LICENSE) © [Elastic](https://www.elastic.co/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Factivecollab%2Felasticsearch-php","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Factivecollab%2Felasticsearch-php","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Factivecollab%2Felasticsearch-php/lists"}