Elasticsearch client for PHP: elasticsearch-php — complete guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Elasticsearch client for PHP (elasticsearch-php): a powerful tool for search and analytics



Elasticsearch is a distributed search and analytics system built on top of Apache Lucene. It allows you to store, search, and analyze large volumes of data in near real-time. To interact with Elasticsearch from PHP applications, there is an official client — elasticsearch-php. This library provides a convenient API for performing all operations: from indexing documents to complex search queries and aggregations.



In this article, we will thoroughly cover the installation, configuration, and main capabilities of elasticsearch-php. You will learn how to connect to a cluster, create an index, add documents, perform searches, and use advanced features such as filtering and data aggregation.



Installing elasticsearch-php



The library is distributed via Composer. To install it, run the following command in the root of your project:



composer require elasticsearch/elasticsearch


After installation, the dependency will appear in the composer.json file. Make sure you have PHP version 7.4 or higher installed, as well as the json extension.



Connecting to the Elasticsearch server



The first step is to create a client. For a local server (by default, Elasticsearch listens on port 9200), the code will look like this:



<?phprequire 'vendor/autoload.php';

use Elastic\\Elasticsearch\\ClientBuilder;

$client = ClientBuilder::create() ->setHosts(['localhost:9200']) ->build();?>


If your server requires authentication (for example, via login/password or API key), pass the parameters:



$client = ClientBuilder::create()    ->setHosts(['https://user:pass@localhost:9200'])    ->setSSLVerification(false) // for development only    ->build();


Working with indices and documents



Elasticsearch stores data in indices (analogous to tables in SQL). Let's create an index products with a simple mapping:



$params = [    'index' => 'products',    'body' => [        'settings' => [            'number_of_shards' => 1,            'number_of_replicas' => 0        ],        'mappings' => [            'properties' => [                'title' => ['type' => 'text'],                'price' => ['type' => 'float'],                'description' => ['type' => 'text'],                'category' => ['type' => 'keyword']            ]        ]    ]];

$response = $client->indices()->create($params);


Now let's add a few documents:



$documents = [    ['title' => 'Dell XPS 15 Laptop', 'price' => 1200.00, 'description' => 'Powerful ultrabook for work', 'category' => 'electronics'],    ['title' => 'Book "PHP for Professionals"', 'price' => 45.50, 'description' => 'Learning PHP at an advanced level', 'category' => 'books'],    ['title' => 'Sony WH-1000XM5 Headphones', 'price' => 350.00, 'description' => 'Wireless headphones with noise cancellation', 'category' => 'electronics']];

foreach ($documents as $id => $doc) { $params = [ 'index' => 'products', 'id' => $id + 1, 'body' => $doc ]; $response = $client->index($params);}


Searching documents



Let's perform a full-text search on the title field:



$params = [    'index' => 'products',    'body' => [        'query' => [            'match' => [                'title' => 'laptop'            ]        ]    ]];

$response = $client->search($params);$hits = $response['hits']['hits'];

foreach ($hits as $hit) { echo "ID: " . $hit['_id'] . " | Title: " . $hit['_source']['title'] . "<br>";}


Filters and aggregations



Elasticsearch supports powerful filtering and data aggregation. For example, let's find all products in the "electronics" category with a price less than 500 and calculate the average price:



$params = [    'index' => 'products',    'body' => [        'query' => [            'bool' => [                'filter' => [                    ['term' => ['category' => 'electronics']],                    ['range' => ['price' => ['lt' => 500]]]                ]            ]        ],        'aggs' => [            'avg_price' => ['avg' => ['field' => 'price']]        ]    ]];

$response = $client->search($params);$avgPrice = $response['aggregations']['avg_price']['value'];echo "Average price: " . $avgPrice;


Conclusion



The elasticsearch-php library provides a full set of tools for integrating Elasticsearch into PHP projects. It supports all key features: indexing, search, filtering, aggregations, and cluster management. The library is actively maintained and updated in sync with new versions of Elasticsearch.



For more detailed information, visit the official documentation on GitHub: elasticsearch-php.

Recommendations