Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
E

elasticsearch

> 后端框架
Open source

The missing elasticsearch ORM for Laravel, Lumen and Native php applications

397 stars0 likes2 views
WebsiteGitHub

About

The missing elasticsearch ORM for Laravel, Lumen and Native php applications

Laravel, Lumen and Native php elasticseach query builder to build complex queries using an elegant syntax

  • Keeps you away from wasting your time by replacing array queries with a simple and elegant syntax you will love.
  • Elasticsearch data model for types and indices inspired from laravel eloquent.
  • Feeling free to create, drop, mapping and reindexing through easy artisan console commands.
  • Lumen framework support.
  • Native php and composer based applications support.
  • Can be used as a laravel scout driver.
  • Dealing with multiple elasticsearch connections at the same time.
  • Awesome pagination based on LengthAwarePagination.
  • Caching queries using a caching layer over query builder built on laravel cache.

Requirements

  • php >= 5.6.6

    See Travis CI Builds.

  • laravel/laravel >= 5.* or laravel/lumen >= 5.* or composer application

Documentation

See Full Documentation.

Installation

Laravel Installation

1) Install package using composer.
bash
$ composer require basemkhirat/elasticsearch
2) Add package service provider ( Basemkhirat\Elasticsearch\Facades\ES::class
	
##### 4) Publishing.

```bash
$ php artisan vendor:publish --provider="Basemkhirat\Elasticsearch\ElasticsearchServiceProvider"

Lumen Installation

1) Install package using composer.
bash
$ composer require basemkhirat/elasticsearch
2) Add package service provider in bootstrap/app.php.
php
$app->register(Basemkhirat\Elasticsearch\ElasticsearchServiceProvider::class);
3) Copy package config directory vendor/basemkhirat/elasticsearch/src/config to root folder alongside with app directory.
4) Making Lumen work with facades by uncommenting this line in bootstrap/app.php.
php
$app->withFacades();

If you don't want to enable working with Lumen facades you can access the query builder using app("es").

php
app("es")->index("my_index")->type("my_type")->get();

# is similar to 

ES::index("my_index")->type("my_type")->get();

Composer Installation

You can install package with any composer-based applications

1) Install package using composer.
bash
$ composer require basemkhirat/elasticsearch
2) Creating a connection.
php
require "vendor/autoload.php";

use Basemkhirat\Elasticsearch\Connection;

$connection = Connection::create([
    'servers' => [
        [
            "host" => '127.0.0.1',
            "port" => 9200,
            'user' => '',
            'pass' => '',
            'scheme' => 'http',
        ],
    ],
    
	// Custom handlers
	// 'handler' => new MyCustomHandler(),

    'index' => 'my_index',
    
    'logging' => [
        'enabled'   => env('ELASTIC_LOGGING_ENABLED',false),
        'level'     => env('ELASTIC_LOGGING_LEVEL','all'),
        'location'  => env('ELASTIC_LOGGING_LOCATION',base_path('storage/logs/elasticsearch.log'))
    ],  
]);

# access the query builder using created connection

$documents = $connection->search("hello")->get();

Configuration (Laravel & Lumen)

After publishing, two configuration files will be created.

  • config/es.php where you can add more than one elasticsearch server.
php
# Here you can define the default connection name.

'default' => env('ELASTIC_CONNECTION', 'default'),

# Here you can define your connections.

'connections' => [
	'default' => [
	    'servers' => [
	        [
	            "host" => env("ELASTIC_HOST", "127.0.0.1"),
	            "port" => env("ELASTIC_PORT", 9200),
	            'user' => env('ELASTIC_USER', ''),
	            'pass' => env('ELASTIC_PASS', ''),
	            'scheme' => env('ELASTIC_SCHEME', 'http'),
	        ]
	    ],
	    
		// Custom handlers
		// 'handler' => new MyCustomHandler(),
		
		'index' => env('ELASTIC_INDEX', 'my_index')
	]
],
 
# Here you can define your indices.
 
'indices' => [
	'my_index_1' => [
	    "aliases" => [
	        "my_index"
	    ],
	    'settings' => [
	        "number_of_shards" => 1,
	        "number_of_replicas" => 0,
	    ],
	    'mappings' => [
	        'posts' => [
                'properties' => [
                    'title' => [
                        'type' => 'string'
                    ]
                ]
	        ]
	    ]
	]
]
  • config/scout.php where you can use package as a laravel scout driver.

Working with console environment (Laravel & Lumen)

With some artisan commands you can do some tasks such as creating or updating settings, mappings and aliases.

Note that all commands are running with --connection=default option, you can change it through the command.

These are all available commands:

List All indices on server

bash
$ php artisan es:indices:list

+----------------------+--------+--------+----------+------------------------+-----+-----+------------+--------------+------------+----------------+
| configured (es.php)  | health | status | index    | uuid                   | pri | rep | docs.count | docs.deleted | store.size | pri.store.size |
+----------------------+--------+--------+----------+------------------------+-----+-----+------------+--------------+------------+----------------+
| yes                  | green  | open   | my_index | 5URW60KJQNionAJgL6Q2TQ | 1   | 0   | 0          | 0            | 260b       | 260b           |
+----------------------+--------+--------+----------+------------------------+-----+-----+------------+--------------+------------+----------------+

Create indices defined in es.php config file

Note that creating operation skips the index if exists.

bash
# Create all indices in config file.

$ php artisan es:indices:create

# Create only 'my_index' index in config file

$ php artisan es:indices:create my_index 

Update indices defined in es.php config file

Note that updating operation updates indices setting, aliases and mapping and doesn't delete the indexed data.

bash
# Update all indices in config file.

$ php artisan es:indices:update

# Update only 'my_index' index in config file

$ php artisan es:indices:update my_index 

Drop index

Be careful when using this command, you will lose your index data!

Running drop command with --force option will skip all confirmation messages.

bash
# Drop all indices in config file.

$ php artisan es:indices:drop

# Drop specific index on sever. Not matter for index to be exist in config file or not.

$ php artisan es:indices:drop my_index 

…

php
"aliases" => [
    "my_index_alias"
]       
  1. Update index with command:
bash
$ php artisan es:indices:update my_index
  1. Create a new index as example my_new_index with your new mapping in configuration file.
bash
$ php artisan es:indices:create my_new_index
  1. Reindex data from my_index into my_new_index with command:
bash
$ php artisan es:indices:reindex my_index my_new_index

# Control bulk size. Adjust it with your server.

$ php artisan es:indices:reindex my_index my_new_index --bulk-size=2000

# Control query scroll value.

$ php artisan es:indices:reindex my_index my_new_index --bulk-size=2000 --scroll=2m

# Skip reindexing errors such as mapper parsing exceptions.

$ php artisan es:indices:reindex my_index my_new_index --bulk-size=2000 --skip-errors 

# Hide all reindexing errors and show the progres bar only.

$ php artisan es:indices:reindex my_index my_new_index --bulk-size=2000 --skip-errors --hide-errors
  1. Remove my_index_alias alias from my_index and add it to my_new_index in configuration file and update with command:
bash
$ php artisan es:indices:update

Usage as a Laravel Scout driver

First, follow Laravel Scout installation.

All you have to do is updating these lines in config/scout.php configuration file.

php
# change the default driver to 'es'
	
'driver' => env('SCOUT_DRIVER', 'es'),
	
# link `es` driver with default elasticsearch connection in config/es.php
	
'es' => [
    'connection' => env('ELASTIC_CONNECTION', 'default'),
],

Have a look at laravel Scout documentation.

Elasticsearch data model

Each index type has a corresponding "Model" which is used to interact with that type. Models allow you to query for data in your types or indices, as well as insert new documents into the type.

Basic usage
php
title;
}
Adding Additional Constraints

The all method will return all of the results in the model's type. Each elasticsearch model serves as a query builder, you may also add constraints to queries, and then use the get() method to retrieve the results:

php
$posts = App\Post::where('status', 1)
               ->orderBy('created_at', 'desc')
               ->take(10)
               ->get();
Retrieving Single Models
php
// Retrieve a model by document key...
$posts = App\Post::find("AVp_tCaAoV7YQD3Esfmp");
Inserting Models

To create a new document, simply create a new model instance, set attributes on the model, then call the save() method:

php
title = $request->title;

        $post->save();
    }
}
Updating Models

The save() method may also be used to update models that already exist. To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method.

php
$post = App\Post::find(1);

$post->title = 'New Post Title';

$post->save();
Deleting Models

To delete a model, call the delete() method on a model instance:

php
$post = App\Post::find(1);

$post->delete();
Query Scopes

Scopes allow you to define common sets of constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all posts that are considered "popular". To define a scope, simply prefix an Eloquent model method with scope.

Scopes should always return a Query instance.

php
where('votes', '>', $votes);
    }

    /**
     * Scope a query to only include active posts.
     *
     * @param \Basemkhirat\Elasticsearch\Query $query
     * @return \Basemkhirat\Elasticsearch\Query
     */
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }
}

Once the scope has been defined, you may call the scope methods when querying the model. However, you do not need to include the scope prefix when calling the method. You can even chain calls to various scopes, for example:

php
$posts = App\Post::popular(100)->active()->orderBy('created_at')->get();
Accessors & Mutators
Defining An Accessor

To define an accessor, create a getFooAttribute method on your model where Foo is the "studly" cased name of the column you wish to access. In this example, we'll define an accessor for the title attribute. The accessor will automatically be called by model when attempting to retrieve the value of the title attribute:

php
title;

Occasionally, you may need to add array attributes that do not have a corresponding field in your index. To do so, simply define an accessor for the value:

php
public function getIsPublishedAttribute()
{
    return $this->attributes['status'] == 1;
}

Once you have created the accessor, just add the value to the appends property on the model:

php
protected $appends = ['is_published'];

Once the attribute has been added to the appends list, it will be included in model's array.

Defining A Mutator

To define a mutator, define a setFooAttribute method on your model where Foo is the "studly" cased name of the column you wish to access. So, again, let's define a mutator for the `ti

Issues· 67 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPcachingelasticsearcheloquentindexing

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架