Top Related Projects
Quick Overview
Elasticsearch-php is the official PHP client for Elasticsearch. It provides a simple and flexible way to interact with Elasticsearch clusters, allowing developers to perform various operations such as indexing, searching, and managing documents and indices.
Pros
- Officially supported by Elastic, ensuring compatibility and regular updates
- Comprehensive documentation and extensive API coverage
- Supports both synchronous and asynchronous requests
- Flexible configuration options for connection pooling and load balancing
Cons
- Steep learning curve for beginners due to the complexity of Elasticsearch
- Performance overhead compared to direct HTTP requests
- Large dependency footprint
- Some advanced Elasticsearch features may require additional configuration
Code Examples
- Creating an Elasticsearch client:
use Elastic\Elasticsearch\ClientBuilder;
$client = ClientBuilder::create()
->setHosts(['localhost:9200'])
->build();
- Indexing a document:
$params = [
'index' => 'my_index',
'id' => '1',
'body' => ['title' => 'Test document', 'content' => 'This is a test']
];
$response = $client->index($params);
- Performing a search:
$params = [
'index' => 'my_index',
'body' => [
'query' => [
'match' => [
'content' => 'test'
]
]
]
];
$results = $client->search($params);
Getting Started
- Install the library using Composer:
composer require elasticsearch/elasticsearch
- Create a client and perform a simple operation:
use Elastic\Elasticsearch\ClientBuilder;
require 'vendor/autoload.php';
$client = ClientBuilder::create()->build();
$response = $client->info();
print_r($response);
This will connect to Elasticsearch on localhost:9200
and retrieve cluster information.
Competitor Comparisons
Elastica is a PHP client for elasticsearch
Pros of Elastica
- More feature-rich with additional abstractions and helper methods
- Supports both synchronous and asynchronous operations
- Extensive documentation and examples
Cons of Elastica
- Slightly higher learning curve due to additional abstractions
- May have slower performance in some cases due to extra layers
Code Comparison
Elastica:
$elasticaClient = new \Elastica\Client();
$index = $elasticaClient->getIndex('my_index');
$type = $index->getType('my_type');
$document = new \Elastica\Document(1, ['name' => 'John Doe']);
$type->addDocument($document);
elasticsearch-php:
$client = \Elasticsearch\ClientBuilder::create()->build();
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 1,
'body' => ['name' => 'John Doe']
];
$response = $client->index($params);
Both libraries provide PHP clients for Elasticsearch, but Elastica offers a more object-oriented approach with additional abstractions. elasticsearch-php, being the official client, provides a lower-level API that closely mirrors the Elasticsearch REST API. The choice between the two depends on your specific needs, with Elastica being more suitable for complex applications requiring additional features, while elasticsearch-php offers a simpler, more direct approach to interacting with Elasticsearch.
Deprecated: Use the official Elasticsearch client for Go at https://github.com/elastic/go-elasticsearch
Pros of elastic
- Written in Go, offering better performance and concurrency
- More comprehensive and feature-rich API
- Active development with frequent updates and releases
Cons of elastic
- Steeper learning curve due to more complex API
- Larger codebase, potentially leading to longer compilation times
- May be overkill for simple Elasticsearch interactions
Code Comparison
elasticsearch-php:
$client = ClientBuilder::create()->build();
$params = [
'index' => 'my_index',
'body' => ['testField' => 'abc']
];
$response = $client->index($params);
elastic:
client, _ := elastic.NewClient()
_, err := client.Index().
Index("my_index").
BodyJson(map[string]interface{}{"testField": "abc"}).
Do(context.Background())
Summary
While elasticsearch-php offers a simpler API and is the official PHP client, elastic provides a more robust and performant solution for Go developers. The choice between the two largely depends on the programming language preference and the complexity of the Elasticsearch interactions required in the project.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Elasticsearch PHP client
This is the official PHP client for Elasticsearch.
Download the latest version of Elasticsearch or sign-up for a free trial of Elastic Cloud.
Contents
- Installation
- Connecting
- Usage
- Versioning
- Backward Incompatible Changes
- Mock the Elasticsearch client
- FAQ
- Contribute
- License
Installation
Refer to the Installation section of the getting started documentation.
Connecting
Refer to the Connecting section of the getting started documentation.
Usage
The elasticsearch-php
client offers 400+ endpoints for interacting with
Elasticsearch. A list of all these endpoints is available in the
official documentation
of Elasticsearch APIs.
Here we reported the basic operation that you can perform with the client: index, search and delete.
- Creating an index
- Indexing a document
- Getting documents
- Searching documents
- Updating documents
- Deleting documents
- Deleting an index
Versioning
This client is versioned and released alongside Elasticsearch server.
To guarantee compatibility, use the most recent version of this library within the major version of the corresponding Enterprise Search implementation.
For example, for Elasticsearch 7.16
, use 7.16
of this library or above, but
not 8.0
.
Compatibility
The Elasticsearch client is compatible with currently maintained PHP versions.
Language clients are forward compatible; meaning that clients support communicating with greater or equal minor versions of Elasticsearch without breaking. It does not mean that the client automatically supports new features of newer Elasticsearch versions; it is only possible after a release of a new client version. For example, a 8.12 client version won't automatically support the new features of the 8.13 version of Elasticsearch, the 8.13 client version is required for that. Elasticsearch language clients are only backwards compatible with default distributions and without guarantees made.
Elasticsearch Version | Elasticsearch-PHP Branch | Supported |
---|---|---|
main | main | |
8.x | 8.x | 8.x |
7.x | 7.x | 7.17 |
Backward Incompatible Changes :boom:
The 8.0.0 version of elasticsearch-php
contains a new implementation compared
with 7.x. It supports PSR-7 for HTTP
messages and PSR-18 for HTTP client
communications.
We tried to reduce the BC breaks as much as possible with 7.x
but there are
some (big) differences:
- we changed the namespace, now everything is under
Elastic\Elasticsearch
- we used the elastic-transport-php library for HTTP communications;
- we changed the
Exception
model, using the namespaceElastic\Elasticsearch\Exception
. All the exceptions extends theElasticsearchException
interface, as in 7.x - we changed the response type of each endpoints using an Elasticsearch response class. This class wraps a a PSR-7 response allowing the access of the body response as array or object. This means you can access the API response as in 7.x, no BC break here! :angel:
- we changed the
ConnectionPool
inNodePool
. Theconnection
naming was ambigous since the objects are nodes (hosts)
You can have a look at the BREAKING_CHANGES file for more information.
Mock the Elasticsearch client
If you need to mock the Elasticsearch client you just need to mock a PSR-18 HTTP Client.
For instance, you can use the php-http/mock-client as follows:
use Elastic\Elasticsearch\ClientBuilder;
use Elastic\Elasticsearch\Response\Elasticsearch;
use Http\Mock\Client;
use Nyholm\Psr7\Response;
$mock = new Client(); // This is the mock client
$client = ClientBuilder::create()
->setHttpClient($mock)
->build();
// This is a PSR-7 response
$response = new Response(
200,
[Elasticsearch::HEADER_CHECK => Elasticsearch::PRODUCT_NAME],
'This is the body!'
);
$mock->addResponse($response);
$result = $client->info(); // Just calling an Elasticsearch endpoint
echo $result->asString(); // This is the body!
We are using the ClientBuilder::setHttpClient()
to set the mock client.
You can specify the response that you want to have using the
addResponse($response)
function. As you can see the $response
is a PSR-7
response object. In this example we used the Nyholm\Psr7\Response
object from
the nyholm/psr7 project. If you are using
PHPUnit you can even mock the ResponseInterface
as
follows:
$response = $this->createMock('Psr\Http\Message\ResponseInterface');
Notice: we added a special header in the HTTP response. This is the product
check header, and it is required for guarantee that elasticsearch-php
is
communicating with an Elasticsearch server 8.0+.
For more information you can read the Mock client section of PHP-HTTP documentation.
FAQ ð®
Where do I report issues with the client?
If something is not working as expected, please open an issue.
Where else can I go to get help?
You can checkout the Elastic community discuss forums.
Contribute ð
We welcome contributors to the project. Before you begin, some useful info...
- If you want to contribute to this project you need to subscribe to a Contributor Agreement.
- Before opening a pull request, please create an issue to discuss the scope of your proposal.
- If you want to send a PR for version
8.0
please use the8.0
branch, for8.1
use the8.1
branch and so on. - 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. If you are not familiar with PHPUnit you can have a look at the reference.
Thanks in advance for your contribution! :heart:
License ð
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot