PHPackages                             codeartmk/opensearch-laravel - 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. [Database &amp; ORM](/categories/database)
4. /
5. codeartmk/opensearch-laravel

ActiveLibrary[Database &amp; ORM](/categories/database)

codeartmk/opensearch-laravel
============================

This package integrates the Opensearch client to work seamlessly with your Laravel Eloquent Model.

v1.0.2(2y ago)122.1k2MITPHPPHP &gt;=8.1

Since Mar 5Pushed 2y ago1 watchersCompare

[ Source](https://github.com/codeartmk/opensearch-laravel)[ Packagist](https://packagist.org/packages/codeartmk/opensearch-laravel)[ RSS](/packages/codeartmk-opensearch-laravel/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (6)Dependencies (3)Versions (7)Used By (0)

Build Opensearch Queries through Eloquent
=========================================

[](#build-opensearch-queries-through-eloquent)

[![Latest Version on Packagist](https://camo.githubusercontent.com/d8fe6db2ab4260d7644d03125370aeb3ecfaacdd2a40be6178a14bcc785858cd/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f64656172746d6b2f6f70656e7365617263682d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/codeartmk/opensearch-laravel)[![Total Downloads](https://camo.githubusercontent.com/54ac4999921cffe1f8c603bf28baa97d87c37c77ae3328fc0dc94f5f947933aa/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636f64656172746d6b2f6f70656e7365617263682d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/codeartmk/opensearch-laravel)

Overview
--------

[](#overview)

This package integrates the Opensearch client to work seamlessly with your Laravel Eloquent Model.

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

[](#installation)

To install the Laravel OpenSearch Plugin, use Composer:

```
composer require codeartmk/opensearch-laravel
```

and then export the configuration with

```
php artisan vendor:publish --provider="Codeart\OpensearchLaravel\OpenSearchServiceProvider" --tag="config"
```

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

[](#basic-usage)

### Setting up the model

[](#setting-up-the-model)

Your models will need to implement the `Codeart\OpensearchLaravel\OpenSearchable` interface, and include the trait `Codeart\OpensearchLaravel\Traits\HasOpenSearchDocuments`.

```
use Codeart\OpensearchLaravel\OpenSearchable;
use Codeart\OpensearchLaravel\Traits\HasOpenSearchDocuments;

class User extends Authenticatable implements OpenSearchable
{
    use HasApiTokens, HasFactory, Notifiable, HasOpenSearchDocuments;

    //rest of the model
}
```

You can override the 3 functions `openSearchMapping`, `openSearchArray`, and `openSearchIndexName` to customize your mapping, the information stored and the index name.

For mapping options look at OpenSearch [mapping documentation](https://opensearch.org/docs/latest/field-types/).

```
use Codeart\OpensearchLaravel\OpenSearchable;
use Codeart\OpensearchLaravel\Traits\HasOpenSearchDocuments;

class User extends Authenticatable implements OpenSearchable
{
    use HasApiTokens, HasFactory, Notifiable, HasOpenSearchDocuments;

    public function openSearchMapping(): array
    {
        return [
            "mapping" => [
                "properties" => [
                    "id" => [ "type" => "integer" ],
                    "first_name" => [ "type" => "text" ],
                    "last_name" => [ "type" => "text" ],
                    "name" => [ "type" => "text" ],
                    "email" => [ "type" => "keyword" ],
                    //...
                ]
            ]
        ];
    }

    public function openSearchArray(): array
    {
        return [
            "id" => $this->id,
            "first_name" => $this->first_name,
            "last_name" => $this->last_name,
            "name" => $this->first_name + " " + $this->last_name,
            "email" => $this->email,
            //...
        ];
    }

    public function openSearchIndexName(): string
    {
        return "users";
    }

    //rest of the model
}
```

Building queries and aggregations
---------------------------------

[](#building-queries-and-aggregations)

Once the model is ready you can start building your queries and aggregation through the `opensearch` method on the class:

```
use App\Models\User;

User::opensearch()
    ->builder()
    ->search([
        Query::make([
            BoolQuery::make([
                Must::make([
                    MatchOne::make("first_name", "John"),
                    BoolQuery::make([
                        Should::make([
                            MatchOne::make('email', 'johndoe@example.com'),
                            MatchOne::make('last_name', 'johndoe@example.com'),
                        ]),
                        'minimum_should_match' => 1
                    ])
                ]),
            ])
        ]),
        Sort::make([
            'id' => 'desc',
        ])
    ])
    ->aggregations([
        Aggregation::make(
            name: "user_names",
            aggregationType: Terms::make(field: 'name',  size: 10000),
            aggregation: Aggregation::make(
                name: 'bucket_truncate',
                aggregationType: BucketSort::make('_key')
            )
        ),
    ])
    ->get();
```

Supported Query DSL queries:
----------------------------

[](#supported-query-dsl-queries)

### Match

[](#match)

```
\Codeart\OpensearchLaravel\Search\SearchQueries\Types\MatchOne::make('name', 'john doe');
```

### Exists

[](#exists)

```
\Codeart\OpensearchLaravel\Search\SearchQueries\Types\Exists::make('description');
```

### Fuzzy

[](#fuzzy)

```
\Codeart\OpensearchLaravel\Search\SearchQueries\Types\Fuzzy::make('speaker', 'HALET');
```

### IDs

[](#ids)

```
\Codeart\OpensearchLaravel\Search\SearchQueries\Types\Ids::make([34229, 91296]);
```

### Prefix

[](#prefix)

```
\Codeart\OpensearchLaravel\Search\SearchQueries\Types\Prefix::make('speaker', 'KING H');
```

### Range

[](#range)

```
\Codeart\OpensearchLaravel\Search\SearchQueries\Types\Range::make('line_id', ['gte' => 10, 'lte' => 20]);
```

### Regexp

[](#regexp)

```
\Codeart\OpensearchLaravel\Search\SearchQueries\Types\Regexp::make('play_name', '[a-zA-Z]amlet');
```

### Wildcard

[](#wildcard)

```
\Codeart\OpensearchLaravel\Search\SearchQueries\Types\Wildcard::make('speaker', 'H*Y');
```

### Match All

[](#match-all)

```
\Codeart\OpensearchLaravel\Search\SearchQueries\Types\MatchAll::make();
```

### Match Phrase Prefix

[](#match-phrase-prefix)

```
\Codeart\OpensearchLaravel\Search\SearchQueries\Types\MatchPhrasePrefix::make('title', 'the rise');
```

### Term

[](#term)

```
\Codeart\OpensearchLaravel\Search\SearchQueries\Types\Term::make('id', 1234);
```

Supported Aggregations
----------------------

[](#supported-aggregations)

### Average

[](#average)

```
\Codeart\OpensearchLaravel\Aggregations\Types\Average::make('taxful_total_price');
```

### Cardinality

[](#cardinality)

```
\Codeart\OpensearchLaravel\Aggregations\Types\Cardinality::make('products.product_id');
```

### Maximum

[](#maximum)

```
\Codeart\OpensearchLaravel\Aggregations\Types\Maximum::make('taxful_total_price');
```

### Minimum

[](#minimum)

```
\Codeart\OpensearchLaravel\Aggregations\Types\Minimum::make('taxful_total_price');
```

### Percentile

[](#percentile)

```
\Codeart\OpensearchLaravel\Aggregations\Types\Percentile::make('taxful_total_price');
```

### Stats

[](#stats)

```
\Codeart\OpensearchLaravel\Aggregations\Types\Stats::make('taxful_total_price');
```

### Sum

[](#sum)

```
\Codeart\OpensearchLaravel\Aggregations\Types\Sum::make('taxful_total_price');
```

### Terms

[](#terms)

```
\Codeart\OpensearchLaravel\Aggregations\Types\Terms::make('company.name', 100);
```

### Bucket Sort

[](#bucket-sort)

[https://opensearch.org/docs/latest/aggregations/pipeline-agg/#bucket\_sort](https://opensearch.org/docs/latest/aggregations/pipeline-agg/#bucket_sort)

```
\Codeart\OpensearchLaravel\Aggregations\Types\BucketSort::make('company_id')
```

We plan to support more in the feature.

Working with indices and documents
----------------------------------

[](#working-with-indices-and-documents)

We offer tools to help you work with Opensearch indices and documents.

### Indices

[](#indices)

We have the methods `create`, `exists`, and `delete` currently.

The optional `$configuration` parameter in the `create` method allows you to customize your [settings](https://opensearch.org/docs/latest/install-and-configure/configuring-opensearch/index-settings/#specifying-a-setting-when-creating-an-index)for your index.

```
use App\Models\User;

User::opensearch()
    ->indices()
    ->create($configuration = []);

User::opensearch()
    ->indices()
    ->delete();

User::opensearch()
    ->indices()
    ->exists();
```

### Documents

[](#documents)

```
use App\Models\User;

User::opensearch()
    ->documents()
    ->createAll();

User::opensearch()
    ->documents()
    ->create($ids);

User::opensearch()
    ->documents()
    ->createOrUpdate($id);

User::opensearch()
    ->documents()
    ->delete($id);
```

### Lazy Loading Relationship

[](#lazy-loading-relationship)

The methods `createAll`, `create`, and `createOrUpdate` all accept a function as a second parameter to allow you to lazy load your relationship when creating documents.

```
use App\Models\User;

User::opensearch()
    ->documents()
    ->create($ids, fn($query) => $query->with('relationship'));
```

Extending the functionality
---------------------------

[](#extending-the-functionality)

If we've missed a search query you need or an aggregation you need, you can easily implement your own and integrate it to work our core functionality.

### Search Query

[](#search-query)

Create a custom class and implement the `SearchQueryType` and `OpenSearchQuery` interfaces. If you were to implement the [Query String](https://opensearch.org/docs/latest/query-dsl/full-text/query-string/) query it would look like the following:

```
use Codeart\OpensearchLaravel\Interfaces\OpenSearchQuery;
use Codeart\OpensearchLaravel\Search\SearchQueries\Types\SearchQueryType;

class MyCustomQuery implements OpenSearchQuery, SearchQueryType
{
    public function __construct(
        private readonly string $query
    ) {}

    public static function make(string $query) {
        return self($query);
    }

    public function toOpenSearchQuery() : array{
        return [
            'query_string' => [
                'query' => $query
            ]
        ];
    }
}
```

and then just call it.

```
use App\Models\User;
use MyNamespace\MyCustomQuery;

User::opensearch()
    ->builder()
    ->search([
        Query::make([
            MyCustomQuery::make('the wind AND (rises OR rising)')
        ]),
    ])
    ->get();
```

### Aggregations

[](#aggregations)

You can achieve the same for aggregations but instead of `SearchQueryType` you need to implement the `AggregationType` inteface.

```
use Codeart\OpensearchLaravel\Interfaces\OpenSearchQuery;
use Codeart\OpensearchLaravel\Aggregations\Types\AggregationType;

class MyCustomAggregation implements OpenSearchQuery, AggregationType
{
    //aggregation logic
}
```

Contact Us
----------

[](#contact-us)

[![](https://camo.githubusercontent.com/511aeef8ace835f926490b9190946dafa6d1e3fdde9d48816c2402b0bc0b1f91/68747470733a2f2f636f64656172742e73332e616d617a6f6e6177732e636f6d2f62616e6e65722e676966)](https://codeart.mk/track/github-opensearch-laravel/)

License
-------

[](#license)

This project is licensed under the MIT License - see the LICENSE file for details.

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity30

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity55

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 ~19 days

Total

6

Last Release

752d ago

Major Versions

v0.0.4-alpha → v1.0.02024-03-13

### Community

Maintainers

![](https://www.gravatar.com/avatar/60a83d189fb253cb06124a83b68e5eacfec625a99f57d97a89835b7c8790a028?d=identicon)[codeart](/maintainers/codeart)

---

Top Contributors

[![ivanjanevmk](https://avatars.githubusercontent.com/u/162157349?v=4)](https://github.com/ivanjanevmk "ivanjanevmk (15 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/codeartmk-opensearch-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/codeartmk-opensearch-laravel/health.svg)](https://phpackages.com/packages/codeartmk-opensearch-laravel)
```

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k117.2M118](/packages/jdorn-sql-formatter)[shopware/platform

The Shopware e-commerce core

3.4k1.5M3](/packages/shopware-platform)[magento/community-edition

Magento 2 (Open Source)

12.2k53.6k13](/packages/magento-community-edition)[smile/elasticsuite

Magento 2 merchandising and search engine built on ElasticSearch

8064.7M49](/packages/smile-elasticsuite)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8351.6M87](/packages/propel-propel1)[wheelpros/fitment-platform-api

Magento 2 (Open Source)

12.1k1.2k](/packages/wheelpros-fitment-platform-api)

PHPackages © 2026

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