PHPackages                             greensight/laravel-elastic-query-specification - 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. greensight/laravel-elastic-query-specification

Abandoned → [ensi/laravel-elastic-query-specification](/?search=ensi%2Flaravel-elastic-query-specification)ArchivedLibrary[Search &amp; Filtering](/categories/search)

greensight/laravel-elastic-query-specification
==============================================

0.1.0(4y ago)15MITPHPPHP ^8.0

Since Sep 28Pushed 4y agoCompare

[ Source](https://github.com/greensight/laravel-elastic-query-specification)[ Packagist](https://packagist.org/packages/greensight/laravel-elastic-query-specification)[ Docs](https://github.com/greensight/laravel-elastic-query-specification)[ RSS](/packages/greensight-laravel-elastic-query-specification/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (1)Dependencies (14)Versions (2)Used By (0)

Laravel Elastic Query Specification
===================================

[](#laravel-elastic-query-specification)

`Deprecated, use https://github.com/ensi-platform/laravel-elastic-query-specification instead`

Extension for [greensight/laravel-elastic-query](https://github.com/greensight/laravel-elastic-query/) to describe queries in a declarative way.

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

[](#installation)

1. Install [greensight/laravel-elastic-query](https://github.com/greensight/laravel-elastic-query/)
2. `composer require greensight/laravel-elastic-query-specification`

Usage // TODO translate to english
----------------------------------

[](#usage--todo-translate-to-english)

Все виды декларативных запросов строятся на основе спецификации. В ней содержатся определения доступных фильтров, сортировок и агрегатов.

```
use Greensight\LaravelElasticQuery\Declarative\Agregating\AllowedAggregate;
use Greensight\LaravelElasticQuery\Declarative\Filtering\AllowedFilter;
use Greensight\LaravelElasticQuery\Declarative\Sorting\AllowedSort;
use Greensight\LaravelElasticQuery\Declarative\Specification\CompositeSpecification;
use Greensight\LaravelElasticQuery\Declarative\Specification\Specification;

class ProductSpecification extends CompositeSpecification
{
    public function __construct()
    {
        parent::__construct();

        $this->allowedFilters([
            'package',
            'active',
            AllowedFilter::exact('cashback', 'cashback.active')->default(true)
        ]);

        $this->allowedSorts(['name', 'rating']);

        $this->allowedAggregates([
            'package',
            AllowedAggregate::minmax('rating')
        ]);

        $this->whereNotNull('package');

        $this->nested('offers', function (Specification $spec) {
            $spec->allowedFilters(['seller_id', 'active']);

            $spec->allowedAggregates([
                'seller_id',
                AllowedAggregate::minmax('price')
            ]);

            $spec->allowedSorts([
                AllowedSort::field('price')->byMin()
            ]);
        });
    }
}
```

Примеры запросов для данной спецификации.

```
{
 "sort": ["+price", "-rating"],
 "filter": {
    "active": true,
    "seller_id": 10
 }
}
```

```
{
 "aggregate": ["price", "rating"],
 "filter": {
    "package": "bottle",
    "seller_id": 10
 }
}
```

Метод `nested` добавляет спецификации для вложенных документов. Имена фильтров, агрегатов и сортировок из них экспортируются в глобальную область видимости без добавления каких-либо префиксов. Если для фильтров допустимо иметь одинаковые имена, то для прочих компонентов нет.

```
$this->nested('nested_field', function (Specification $spec) { ... })
$this->nested('nested_field', new SomeSpecificationImpl());
```

В спецификациях для вложенных документов могут использоваться только поля этих документов.

Допустимо добавлять несколько спецификаций для одного и того же поля типа `nested`.

Ограничения `where*` позволяют устанавливать дополнительные программные условия отбора, которые не могут быть изменены клиентом. Ограничения, заданные в корневой спецификации, применяются всегда. Ограничения во вложенных спецификациях идут только как дополнения к добавляемым в запрос фильтрам, агрегатам или сортировкам. Например, если во вложенной спецификации нет ни одного активного фильтра, то в раздел фильтров запроса к Elasticsearch ограничения из этой спецификации не попадут.

Метод `allowedFilters` определяет доступные для клиента фильтры. Каждый фильтр обязательно содержит уникальное в пределах спецификации имя. В то же время, в корневой и вложенной спецификациях или в разных вложенных спецификациях, имена могут повторяться. Все фильтры с одинаковыми именами будут заполнены одним значением из параметров запроса.

Кроме имени самого фильтра можно отдельно задать имя поля в индексе, для которого он применяется, и значение по умолчанию.

```
$this->allowedFilters([AllowedFilter::exact('name', 'field')->default(500)]);

// the following statements are equivalent
$this->allowedFilters(['name']);
$this->allowedFilters([AllowedFilter::exact('name', 'name')]);
```

Виды фильтров

```
AllowedFilter::exact('name', 'field');  // Значение поля проверяется на равенство одному из заданных
AllowedFilter::exists('name', 'field'); // Проверяется, что поле присутствует в документе и имеет ненулевое значение
```

Доступные клиенту сортировки добавляются методом `allowedSorts`. Направление сортировки задается в ее имени. Знак `+` или отсутствие знака соответствует порядку по возрастанию, `-` - порядку по убыванию. По умолчанию используется сортировка по возрастанию с выбором минимального, в случае нескольких значений в поле.

```
$this->allowedSorts([AllowedSort::field('name', 'field')]);

// the following statements are equivalent
$this->allowedSorts(['name']);
$this->allowedSorts([AllowedSort::field('+name', 'name')]);
$this->allowedSorts([AllowedSort::field('+name', 'name')->byMin()]);

// set the sorting mode
$this->allowedSorts([AllowedSort::field('name', 'field')->byMin()]);
$this->allowedSorts([AllowedSort::field('name', 'field')->byMax()]);
$this->allowedSorts([AllowedSort::field('name', 'field')->byAvg()]);
$this->allowedSorts([AllowedSort::field('name', 'field')->bySum()]);
$this->allowedSorts([AllowedSort::field('name', 'field')->byMedian()]);
```

Для сортировки из вложенной спецификации учитываются все ограничения и активные фильтры из этой же спецификации.

Агрегаты объявляются методом `allowedAggregates`. Клиент в параметрах запроса указывает список имен агрегатов, результаты которых он ожидает в ответе.

```
$this->allowedAggregates([AllowedAggregate::terms('name', 'field')]);

// the following statements are equivalent
$this->allowedAggregates(['name']);
$this->allowedAggregates([AllowedAggregate::terms('name', 'name')]);
```

Виды агрегатов

```
AllowedAggregate::terms('name', 'field');   // Get all variants of attribute values
AllowedAggregate::minmax('name', 'field');  // Get min and max attribute values
```

Агрегаты из вложенных спецификаций добавляются в запрос к Elasticsearch со всеми ограничениями и активными фильтрами.

Поиск документов
----------------

[](#поиск-документов)

```
use Greensight\LaravelElasticQuery\Declarative\SearchQueryBuilder;
use Greensight\LaravelElasticQuery\Declarative\QueryBuilderRequest;

class ProductsSearchQuery extends SearchQueryBuilder
{
    public function __construct(QueryBuilderRequest $request)
    {
        parent::__construct(ProductsIndex::query(), new ProductSpecification(), $request);
    }
}
```

```
class ProductsController
{
    // ...
    public function index(ProductsSearchQuery $query)
    {
        return ProductResource::collection($query->get());
    }
}
```

Расчет сводных показателей
--------------------------

[](#расчет-сводных-показателей)

```
use Greensight\LaravelElasticQuery\Declarative\AggregateQueryBuilder;
use Greensight\LaravelElasticQuery\Declarative\QueryBuilderRequest;

class ProductsAggregateQuery extends AggregateQueryBuilder
{
    public function __construct(QueryBuilderRequest $request)
    {
        parent::__construct(ProductsIndex::aggregate(), new ProductSpecification(), $request);
    }
}
```

```
class ProductsController
{
    // ...
    public function totals(ProductsAggregateQuery $query)
    {
        return new ProductAggregateResource($query->get());
    }
}
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details.

### Testing

[](#testing)

1. composer install
2. npm i
3. Start Elasticsearch in your preferred way.
4. Copy `phpunit.xml.dist` to `phpunit.xml` and set correct env variables there
5. composer test

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

License
-------

[](#license)

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

###  Health Score

21

—

LowBetter than 18% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 66.7% of commits — single point of failure

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

1733d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/58d505cd6b2551974b0c076d133fd9a3c9cd635bbf308adb17a6399bd3b63232?d=identicon)[Arrilot](/maintainers/Arrilot)

---

Top Contributors

[![arrilot](https://avatars.githubusercontent.com/u/2826480?v=4)](https://github.com/arrilot "arrilot (4 commits)")[![zix2](https://avatars.githubusercontent.com/u/51262118?v=4)](https://github.com/zix2 "zix2 (2 commits)")

---

Tags

laravelgreensightlaravel-elastic-query-specification

###  Code Quality

TestsPest

Static AnalysisPsalm

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/greensight-laravel-elastic-query-specification/health.svg)

```
[![Health](https://phpackages.com/badges/greensight-laravel-elastic-query-specification/health.svg)](https://phpackages.com/packages/greensight-laravel-elastic-query-specification)
```

###  Alternatives

[spatie/laravel-health

Monitor the health of a Laravel application

87411.3M153](/packages/spatie-laravel-health)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[mailerlite/laravel-elasticsearch

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

935572.3k2](/packages/mailerlite-laravel-elasticsearch)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

815320.5k3](/packages/defstudio-telegraph)[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.3M42](/packages/spatie-laravel-pdf)[laravel/ai

The official AI SDK for Laravel.

9782.1M162](/packages/laravel-ai)

PHPackages © 2026

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