News

A Fluent PHP Elasticsearch Query Builder

Published
A Fluent PHP Elasticsearch Query Builder image

The elasticsearch-builder package for PHP offers a clean, fluent, immutable, and type-safe query builder for Elasticsearch. This package works seamlessly with the official Elasticsearch PHP client, and offers a clean API over writing queries by hand:

use Elastic\Elasticsearch\ClientBuilder;
use Bonu\ElasticsearchBuilder\QueryBuilder;
use Bonu\ElasticsearchBuilder\Query\TermQuery;
use Bonu\ElasticsearchBuilder\Query\BoolQuery;
use Bonu\ElasticsearchBuilder\Query\MatchQuery;
 
$builder = new QueryBuilder('products')
->query(new TermQuery('ean', 'foo_bar_123')->boost(12))
->query(new BoolQuery()
->should(new MatchQuery('name', 'foo'))
->should(new MatchQuery('description', 'bar'))
->boost(5)
)
->size(20);
 
$client = ClientBuilder::create()->build();
$products = $client->search($builder->build());

Developers might prefer a fluent interface over more complex arrays or raw JSON when using the client directly:

// Using the client with JSON strings
$json = '{
"query" : {
"match" : {
"testField" : "abc"
}
}
}';
 
$params = [
'index' => 'my_index',
'body' => $json
];
 
$results = $client->search($params);

I recommend getting familiar with Elasticsearch and the PHP client docs before using this package. Elasticsearch is a powerful platform for advanced search features, observability, and more.

Main Features

  • Fully fluent & chainable API
  • Zero dependencies beyond the official Elasticsearch PHP SDK
  • Easy creation of reusable composite queries
  • 100% type-hinted and IDE-friendly
  • PHP 8.4+

You can get started with this package on GitHub: php-elasticsearch-builder.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Filed in

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
NativePHP v4: Build Native iOS and Android UI in Blade image

NativePHP v4: Build Native iOS and Android UI in Blade

Read article
Laravel Lock: Distributed Locks for Models and Routes image

Laravel Lock: Distributed Locks for Models and Routes

Read article
Laravel Image Responses: Serve Resized Images From Routes image

Laravel Image Responses: Serve Resized Images From Routes

Read article
Pause All Laravel Queues During a Deploy image

Pause All Laravel Queues During a Deploy

Read article
Laravel Terminal UI for the artisan dev Command image

Laravel Terminal UI for the artisan dev Command

Read article
Pause All Queues and a New artisan dev UI in Laravel 13.25 image

Pause All Queues and a New artisan dev UI in Laravel 13.25

Read article