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 →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article