Elasticsearch Client for PHP: elasticsearch-php
Elasticsearch is a powerful distributed search engine and analytical database built on Apache Lucene. To interact with it from PHP applications, there is an official client — elasticsearch-php. This library provides a convenient and complete API for all operations: from indexing documents to complex full-text queries and aggregations.
Installation and Connection
Installation is done via Composer, the standard package manager for PHP:
composer require elasticsearch/elasticsearchAfter installation, you need to create a client instance, specifying the host (or multiple hosts) of your Elasticsearch cluster:
<?phprequire 'vendor/autoload.php';
use Elastic\\Elasticsearch\\ClientBuilder;
$client = ClientBuilder::create() ->setHosts(['http://localhost:9200']) ->build();?>For a secure connection (HTTPS, authentication), you can pass additional parameters:
$client = ClientBuilder::create() ->setHosts(['https://user:password@my-elastic.cloud:9243']) ->setSSLVerification(false) // for testing only! ->build();Basic Data Operations
Creating an Index
An index in Elasticsearch is analogous to a database in SQL. Before saving data, you can explicitly create it with a mapping:
$params = [ 'index' => 'products', 'body' => [ 'settings' => [ 'number_of_shards' => 1, 'number_of_replicas' => 1 ], 'mappings' => [ 'properties' => [ 'title' => ['type' => 'text'], 'price' => ['type' => 'float'], 'created_at' => ['type' => 'date'] ] ] ]];
$response = $client->indices()->create($params);Indexing a Document (Add/Update)
To add a single document, use the index method:
$params = [ 'index' => 'products', 'id' => '1', 'body' => [ 'title' => 'ASUS ROG Laptop', 'price' => 120000.00, 'created_at' => '2025-01-15' ]];
$response = $client->index($params);If a document with the same id already exists, it will be overwritten. For partial updates, use update.
Getting a Document
$params = [ 'index' => 'products', 'id' => '1'];
$response = $client->get($params);$document = $response['_source'];echo $document['title']; // ASUS ROG LaptopDeleting a Document
$params = [ 'index' => 'products', 'id' => '1'];
$response = $client->delete($params);Search and Filtering
The most powerful feature of Elasticsearch is full-text search. Example of searching for products by name:
$params = [ 'index' => 'products', 'body' => [ 'query' => [ 'match' => [ 'title' => 'laptop' ] ] ]];
$response = $client->search($params);
// Processing resultsforeach ($response['hits']['hits'] as $hit) { echo 'ID: ' . $hit['_id'] . ', Title: ' . $hit['_source']['title'] . "";}You can combine conditions using bool queries:
$params = [ 'index' => 'products', 'body' => [ 'query' => [ 'bool' => [ 'must' => [ ['match' => ['title' => 'laptop']] ], 'filter' => [ ['range' => ['price' => ['gte' => 50000