PHPackages                             ykan/elastickit - 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. ykan/elastickit

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

ykan/elastickit
===============

Elasticsearch DSL query builder for PHP

v8.0.0(3w ago)7291MITPHPPHP ^8.1CI passing

Since Jun 7Pushed 2w ago1 watchersCompare

[ Source](https://github.com/ykan821/ElasticKit)[ Packagist](https://packagist.org/packages/ykan/elastickit)[ RSS](/packages/ykan-elastickit/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (9)Versions (9)Used By (1)

ElasticKit
==========

[](#elastickit)

> [中文](README.zh.md) | English

[![Tests](https://github.com/ykan821/ElasticKit/actions/workflows/ci.yml/badge.svg)](https://github.com/ykan821/ElasticKit/actions/workflows/ci.yml)[![PHP](https://camo.githubusercontent.com/6019badc6def8fa93f0ea037e112670fb5f01199d7626039f0856d26cbee6b7d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f796b616e2f656c61737469636b6974)](https://packagist.org/packages/ykan/elastickit)[![License](https://camo.githubusercontent.com/9e23bd989f73c40809f863da373cba007fde18866e63545304d693edc7189bf6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f796b616e2f656c61737469636b6974)](https://packagist.org/packages/ykan/elastickit)

A PHP Elasticsearch DSL query builder covering queries, aggregations, CRUD, bulk writes, and zero-downtime rebuilds.

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

[](#installation)

```
composer require ykan/elastickit:^8

```

> Requires PHP 8.1+ and Elasticsearch 8.x. The `elasticsearch-php` dependency is installed automatically.

Quick Start
-----------

[](#quick-start)

```
use ElasticKit\Index\Index;

// 1. Register the client
$client = \Elastic\Elasticsearch\ClientBuilder::create()
    ->setHosts(['http://localhost:9200'])->build();
Index::setClient($client);

// 2. Define an index
class ProductIndex extends Index
{
    protected string $name = 'products';
    protected array $mappings = [
        'properties' => [
            'title'  => ['type' => 'text'],
            'price'  => ['type' => 'float'],
            'status' => ['type' => 'keyword'],
        ],
    ];
}

// 3. Search
$results = ProductIndex::query()
    ->match('title', 'elasticsearch')
    ->get();

$hits = $results->docs();   // [['title' => '...'], ...]
$total = $results->total(); // null unless $trackTotalHits = true (see Pagination & cursor)
```

DSL Examples
------------

[](#dsl-examples)

ElasticKit's DSL stays close to the native ES API to minimize cognitive load — if you know ES DSL, the transfer is smooth. Every query type is a dedicated `Node` class whose method names mirror ES parameters.

Expand### Compound query

[](#compound-query)

```
$results = ProductIndex::query()
    ->bool([
        'must'   => fn ($q) => $q->match('title', 'elasticsearch'),
        'filter' => fn ($q) => $q
            ->range('price', [10, 100])
            ->when($status, fn ($q) => $q->term('status', $status)),  // conditional filter
    ])
    ->highlight('title')
    ->sort('price', 'asc')
    ->size(20)
    ->get();
```

```
{
  "query": {
    "bool": {
      "must": [{ "match": { "title": "elasticsearch" } }],
      "filter": [
        { "range": { "price": { "gte": 10, "lte": 100 } } },
        { "term": { "status": "published" } }
      ]
    }
  },
  "highlight": { "fields": { "title": {} } },
  "sort": [{ "price": "asc" }],
  "size": 20
}
```

### OOP style

[](#oop-style)

Build each clause separately, then combine them into a query:

```
use ElasticKit\DSL\Queries\Compound\Boolean;
use ElasticKit\DSL\Queries\FullText\Match_;
use ElasticKit\DSL\Queries\TermLevel\Range;
use ElasticKit\DSL\Queries\TermLevel\Term;

// Build the clauses
$status = Term::create('status', 'published')->boost(1.5);
$title  = Match_::create('title', 'elasticsearch');

// Combine into a bool query
$bool = Boolean::create()->must($title)->filter($status);
if ($filterByPrice) {
    $bool->filter(Range::create('price', [10, 100]));
}

// Execute
$results = ProductIndex::query()->bool($bool)->size(20)->get();
```

### Aggregations

[](#aggregations)

```
$results = ProductIndex::query()
    ->matchAll()
    ->aggs('status_counts', fn ($agg) => $agg->terms('status'))
    ->aggs('price_stats', fn ($agg) => $agg->stats('price'))
    ->size(0)
    ->get();

$aggs = $results->aggregations();
```

### kNN search

[](#knn-search)

```
$results = ProductIndex::query()
    ->knn(fn ($k) => $k
        ->field('embedding')
        ->queryVector([0.12, 0.45, 0.78, /* ... */])
        ->numCandidates(100))
    ->size(10)
    ->get();
```

### Raw array

[](#raw-array)

```
$query = Query::create([
    'query' => [
        'bool' => [
            'must'   => fn ($q) => $q->match('title', 'elasticsearch'),  // array may nest closures
            'filter' => fn ($q) => $q->term('status', 'published'),
        ],
    ],
    'size' => 20,
    'sort' => [['price' => 'asc']],
]);
```

### Clause appending (ClausesSupport)

[](#clause-appending-clausessupport)

The clauses of a `bool` query (must / should / filter / must\_not) **append** — repeated calls accumulate, they don't overwrite:

```
$q->bool(fn ($b) => $b->must($q1));   // must: [q1]
$q->bool(fn ($b) => $b->must($q2));   // must: [q1, q2]
```

> `dis_max`, `span_or`, `span_near` and other array-clause containers behave the same way.

### Flexible arguments

[](#flexible-arguments)

The same method accepts multiple input forms — use whichever suits:

```
$q->term('status', 'published');                                     // string
$q->term(['status' => 'published']);                                 // array
$q->term(fn ($t) => $t->field('status')->value('published'));        // closure
$q->term(Term::create('status', 'published'));                       // object
```

Index Examples
--------------

[](#index-examples)

Around the `Index` base class, dedicated classes cover routine index operations — pagination, CRUD, bulk writes, index management, zero-downtime rebuilds, and event hooks.

Expand### Pagination &amp; cursor

[](#pagination--cursor)

```
// pagination
$results = ProductIndex::query()
    ->match('title', 'elasticsearch')
    ->paginate($page, $perPage);

$results->lastPage();
$results->items();
$results->toPaginator();  // convert to a framework paginator (requires registering a Paginator Resolver)

// batch iteration (large exports / batch processing; yields a Results per batch)
foreach (ProductIndex::query()->chunk() as $results) {
    foreach ($results->docs() as $doc) {
        // ...
    }
}

// per-hit iteration (exports / per-row processing; yields one hit: _id/_score/_source)
foreach (ProductIndex::query()->cursor() as $hit) {
    $doc = $hit['_source'];
    // ...
}
```

> **Pagination needs totals, which are opt-in.** `Index` defaults `$trackTotalHits = false`, so `total()`/`lastPage()` return `null` and `toPaginator()` throws. Set `protected int|bool $trackTotalHits = true;` (or a count cap) on the index for page-count pagination, or use `hasMorePages()` / `chunk()` / `cursor()` for total-less iteration.

### Document CRUD

[](#document-crud)

```
ProductIndex::doc(1)->save(['title' => 'Hello', 'price' => 99.9]);

$doc = ProductIndex::doc(1);
$doc->source();  // ['title' => 'Hello', 'price' => 99.9]

$doc->update(['price' => 89.9]);
$doc->delete();
```

### Bulk operations

[](#bulk-operations)

```
use ElasticKit\Index\Bulk;

$bulk = new Bulk(new ProductIndex());

$bulk->batchSize(500)
    ->index(1, ['title' => 'A', 'price' => 10])
    ->index(2, ['title' => 'B', 'price' => 20])
    ->update(3, ['price' => 15])
    ->delete(4)
    ->flush();
```

### Index management

[](#index-management)

```
use ElasticKit\Index\Manager;

$manager = new Manager(new ProductIndex());

$manager->create();       // create the index
$manager->exists();       // bool
$manager->putMapping();   // update the mapping
$manager->delete();       // delete the index
```

### Zero-downtime rebuild

[](#zero-downtime-rebuild)

```
use ElasticKit\Index\Rebuild;

// 1. Define the data source in an Index subclass
class ProductIndex extends Index
{
    public function source(array $context = []): iterable
    {
        foreach (Db::table('products')->cursor() as $row) {
            yield $row['id'] => $row;
        }
    }
}

// 2. Run the rebuild (creates a new index -> imports -> swaps the alias)
$result = (new Rebuild(new ProductIndex()))
    ->batchSize(500)
    ->run();

// $result = ['newIndex' => 'products_20260607_120000', 'oldIndex' => 'products_20260601_090000']

// 3. Clean up old indices or roll back
(new Rebuild(new ProductIndex()))->clean($result['oldIndex']);
(new Rebuild(new ProductIndex()))->rollback($result['oldIndex']);
```

### Event listening

[](#event-listening)

```
use ElasticKit\Index\Support\Event;
use ElasticKit\Index\Support\EventDispatcher;

EventDispatcher::listen('search.query.after', function (Event $e) {
    Log::info("Search on {$e->index}", [
        'dsl' => $e->dsl,
        'duration' => $e->duration,
    ]);
});

EventDispatcher::listen('search.*', function (Event $e) {
    Log::debug($e->name);
});
```

Documentation
-------------

[](#documentation)

- [Guide](docs/guide.md) — an e-commerce order scenario, the full flow from install to production
- [Index docs](docs/index.md) — search, CRUD, bulk operations, zero-downtime rebuild, events
- [Changelog](CHANGELOG.md)
- [Elasticsearch official docs](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl.html) — query types and parameter reference

License
-------

[](#license)

MIT

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance96

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity48

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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

Every ~5 days

Total

7

Last Release

24d ago

Major Versions

v7.0.0-beta.1 → v8.0.0-beta.12026-06-01

7.x-dev → v8.0.0-beta.42026-06-07

PHP version history (2 changes)v7.0.0-beta.1PHP &gt;=7.2

v8.0.0-beta.1PHP ^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/120786616?v=4)[ykan](/maintainers/ykan821)[@ykan821](https://github.com/ykan821)

---

Top Contributors

[![ykan821](https://avatars.githubusercontent.com/u/120786616?v=4)](https://github.com/ykan821 "ykan821 (86 commits)")

---

Tags

dslelasticsearchelasticsearch-phpphpelasticsearchquerybuilderDSL

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/ykan-elastickit/health.svg)

```
[![Health](https://phpackages.com/badges/ykan-elastickit/health.svg)](https://phpackages.com/packages/ykan-elastickit)
```

###  Alternatives

[mailerlite/laravel-elasticsearch

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

936603.4k2](/packages/mailerlite-laravel-elasticsearch)[jeroen-g/explorer

Next-gen Elasticsearch driver for Laravel Scout.

399672.8k](/packages/jeroen-g-explorer)

PHPackages © 2026

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