PHPackages                             edwinhoksberg/elasticsearch-query-builder - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Search &amp; Filtering](/categories/search)
4. /
5. edwinhoksberg/elasticsearch-query-builder

ActiveLibrary[Search &amp; Filtering](/categories/search)

edwinhoksberg/elasticsearch-query-builder
=========================================

Build and execute an Elasticsearch search query using a fluent PHP API

7.0.0(2y ago)04MITPHPPHP ^8.0

Since Dec 22Pushed 2y agoCompare

[ Source](https://github.com/EdwinHoksberg/elasticsearch-query-builder)[ Packagist](https://packagist.org/packages/edwinhoksberg/elasticsearch-query-builder)[ Docs](https://github.com/edwinhoksberg/elasticsearch-query-builder)[ RSS](/packages/edwinhoksberg-elasticsearch-query-builder/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (2)Used By (0)

Build and execute ElasticSearch queries using a fluent PHP API
==============================================================

[](#build-and-execute-elasticsearch-queries-using-a-fluent-php-api)

[![Latest Version on Packagist](https://camo.githubusercontent.com/c6b2227dd6f4372ca788918ffb15db49e5d7c803ec2a746f0c01ddd893d4ff8d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f656477696e686f6b73626572672f656c61737469637365617263682d71756572792d6275696c6465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/edwinhoksberg/elasticsearch-query-builder)[![Tests](https://github.com/edwinhoksberg/elasticsearch-query-builder/actions/workflows/run-tests.yml/badge.svg)](https://github.com/edwinhoksberg/elasticsearch-query-builder/actions/workflows/run-tests.yml)[![Total Downloads](https://camo.githubusercontent.com/4cc5a6e50eb267c1591d56f923b5a2c3b1a216f2cf3ecece0f329542f0ff26c0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f656477696e686f6b73626572672f656c61737469637365617263682d71756572792d6275696c6465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/edwinhoksberg/elasticsearch-query-builder)

---

This package is a *lightweight* query builder for ElasticSearch. It was specifically built for our [elasticsearch-search-string-parser](https://github.com/spatie/elasticsearch-search-string-parser) so it covers most use-cases but might lack certain features. We're always open for PRs if you need anything specific!

```
use EdwinHoksberg\ElasticsearchQueryBuilder\Aggregations\MaxAggregation;
use EdwinHoksberg\ElasticsearchQueryBuilder\Builder;
use EdwinHoksberg\ElasticsearchQueryBuilder\Queries\MatchQuery;

$client = Elastic\Elasticsearch\ClientBuilder::create()->build();

$companies = (new Builder($client))
    ->index('companies')
    ->addQuery(MatchQuery::create('name', 'spatie', fuzziness: 3))
    ->addAggregation(MaxAggregation::create('score'))
    ->search();
```

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require edwinhoksberg/elasticsearch-query-builder
```

Basic usage
-----------

[](#basic-usage)

The only class you really need to interact with is the `EdwinHoksberg\ElasticsearchQueryBuilder\Builder` class. It requires an `\Elastic\Elasticsearch\Client` passed in the constructor. Take a look at the [ElasticSearch SDK docs](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/installation.html) to learn more about connecting to your ElasticSearch cluster.

The `Builder` class contains some methods to [add queries](#adding-queries), [aggregations](#adding-aggregations), [sorts](#adding-sorts), [fields](#retrieve-specific-fields) and some extras for [pagination](#pagination). You can read more about these methods below. Once you've fully built-up the query you can use `$builder->search()` to execute the query or `$builder->getPayload()` to get the raw payload for ElasticSearch.

```
use EdwinHoksberg\ElasticsearchQueryBuilder\Queries\RangeQuery;
use EdwinHoksberg\ElasticsearchQueryBuilder\Builder;

$client = Elastic\Elasticsearch\ClientBuilder::create()->build();

$builder = new Builder($client);

$builder->addQuery(RangeQuery::create('age')->gte(18));

$results = $builder->search(); // raw response from ElasticSearch
```

Adding queries
--------------

[](#adding-queries)

The `$builder->addQuery()` method can be used to add any of the available `Query` types to the builder. The available query types can be found below or in the `src/Queries` directory of this repo. Every `Query` has a static `create()` method to pass its most important parameters.

Adding sorts
------------

[](#adding-sorts)

The `Builder` (and some aggregations) has a `addSort()` method that takes a `Sort` instance to sort the results. You can read more about how sorting works in [the ElasticSearch docs](https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html).

```
use EdwinHoksberg\ElasticsearchQueryBuilder\Sorts\Sort;

$builder
    ->addSort(Sort::create('age', Sort::DESC))
    ->addSort(
        Sort::create('score', Sort::ASC)
            ->unmappedType('long')
            ->missing(0)
    );
```

Retrieve specific fields
------------------------

[](#retrieve-specific-fields)

The `fields()` method can be used to request specific fields from the resulting documents without returning the entire `_source` entry. You can read more about the specifics of the fields parameter in [the ElasticSearch docs](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-fields.html).

```
$builder->fields('user.id', 'http.*.status');
```

Pagination
----------

[](#pagination)

Finally the `Builder` also features a `size()` and `from()` method for the corresponding ElasticSearch search parameters. These can be used to build a paginated search. Take a look the following example to get a rough idea:

```
use EdwinHoksberg\ElasticsearchQueryBuilder\Builder;

$pageSize = 100;
$pageNumber = $_GET['page'] ?? 1;

$pageResults = (new Builder(Elastic\Elasticsearch\ClientBuilder::create()))
    ->size($pageSize)
    ->from(($pageNumber - 1) * $pageSize)
    ->search();
```

Testing
-------

[](#testing)

```
composer test
```

Credits
-------

[](#credits)

- [Edwin Hoksberg](https://github.com/edwinhoksberg)
- [Alex Vanderbist](https://github.com/alexvanderbist)
- [Ruben Van Assche](https://github.com/rubenvanassche)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity3

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor2

2 contributors hold 50%+ of commits

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

872d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/8e4d5803cd09a66d49af984103219fa0fededf18e34b1dc488905e8eed337395?d=identicon)[EdwinHoksberg](/maintainers/EdwinHoksberg)

---

Top Contributors

[![AlexVanderbist](https://avatars.githubusercontent.com/u/6287961?v=4)](https://github.com/AlexVanderbist "AlexVanderbist (36 commits)")[![EdwinHoksberg](https://avatars.githubusercontent.com/u/6866019?v=4)](https://github.com/EdwinHoksberg "EdwinHoksberg (20 commits)")[![freekmurze](https://avatars.githubusercontent.com/u/483853?v=4)](https://github.com/freekmurze "freekmurze (7 commits)")[![rubenvanassche](https://avatars.githubusercontent.com/u/619804?v=4)](https://github.com/rubenvanassche "rubenvanassche (7 commits)")[![AdrianMrn](https://avatars.githubusercontent.com/u/12762044?v=4)](https://github.com/AdrianMrn "AdrianMrn (5 commits)")[![adevneverdies](https://avatars.githubusercontent.com/u/1610989?v=4)](https://github.com/adevneverdies "adevneverdies (1 commits)")[![imdhemy](https://avatars.githubusercontent.com/u/22864831?v=4)](https://github.com/imdhemy "imdhemy (1 commits)")

---

Tags

searchelasticsearchelasticsearch-query-builder

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

![Health badge](/badges/edwinhoksberg-elasticsearch-query-builder/health.svg)

```
[![Health](https://phpackages.com/badges/edwinhoksberg-elasticsearch-query-builder/health.svg)](https://phpackages.com/packages/edwinhoksberg-elasticsearch-query-builder)
```

###  Alternatives

[elasticsearch/elasticsearch

PHP Client for Elasticsearch

5.3k178.3M943](/packages/elasticsearch-elasticsearch)[spatie/elasticsearch-query-builder

Build and execute an Elasticsearch search query using a fluent PHP API

183614.7k5](/packages/spatie-elasticsearch-query-builder)[matchish/laravel-scout-elasticsearch

Search among multiple models with ElasticSearch and Laravel Scout

7431.6M2](/packages/matchish-laravel-scout-elasticsearch)[10up/elasticpress

Supercharge WordPress with Elasticsearch.

1.3k374.3k6](/packages/10up-elasticpress)[opensearch-project/opensearch-php

PHP Client for OpenSearch

15024.3M65](/packages/opensearch-project-opensearch-php)[mailerlite/laravel-elasticsearch

An easy way to use the official PHP ElasticSearch client in your Laravel applications.

934529.3k2](/packages/mailerlite-laravel-elasticsearch)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
