SkillAgentSearch skills...

Elasticsearch

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

Install / Use

/learn @basemkhirat/Elasticsearch

README

<p align="center"> <!-- <a href="https://travis-ci.org/basemkhirat/elasticsearch"><img src="https://travis-ci.org/basemkhirat/elasticsearch.svg?branch=master" alt="Build Status"></a> --> <a href="https://packagist.org/packages/basemkhirat/elasticsearch"><img src="https://poser.pugx.org/basemkhirat/elasticsearch/v/stable.svg" alt="Latest Stable Version"></a> <a href="https://packagist.org/packages/basemkhirat/elasticsearch"><img src="https://poser.pugx.org/basemkhirat/elasticsearch/d/total.svg" alt="Total Downloads"></a> <a href="https://packagist.org/packages/basemkhirat/elasticsearch"><img src="https://poser.pugx.org/basemkhirat/elasticsearch/license.svg" alt="License"></a> </p>

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

<u>Laravel Installation</u>

1) Install package using composer.
$ composer require basemkhirat/elasticsearch
2) Add package service provider (< laravel 5.5).
Basemkhirat\Elasticsearch\ElasticsearchServiceProvider::class
3) Add package alias (< laravel 5.5).
'ES' => Basemkhirat\Elasticsearch\Facades\ES::class
4) Publishing.
$ php artisan vendor:publish --provider="Basemkhirat\Elasticsearch\ElasticsearchServiceProvider"

<u>Lumen Installation</u>

1) Install package using composer.
$ composer require basemkhirat/elasticsearch
2) Add package service provider in bootstrap/app.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.
$app->withFacades();

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

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

# is similar to 

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

<u>Composer Installation</u>

You can install package with any composer-based applications

1) Install package using composer.
$ composer require basemkhirat/elasticsearch
2) Creating a connection.
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.
# 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

$ 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.

# 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.

# 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.

# 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 

Reindexing data (with zero downtime)

First, why reindexing?

Changing index mapping doesn't reflect without data reindexing, otherwise your search results will not work on the right way.

To avoid down time, your application should work with index alias not index name.

The index alias is a constant name that application should work with to avoid change index names.

Assume that we want to change mapping for my_index, this is how to do that:
  1. Add alias as example my_index_alias to my_index configuration and make sure that application is working with.
"aliases" => [
    "my_index_alias"
]       
  1. Update index with command:
$ php artisan es:indices:update my_index
  1. Create a new index as example my_new_index with your new mapping in configuration file.
$ php artisan es:indices:create my_new_index
  1. Reindex data from my_index into my_new_index with command:
$ 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:
$ 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.

# 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 int

Related Skills

View on GitHub
GitHub Stars402
CategoryDevelopment
Updated10mo ago
Forks127

Languages

PHP

Security Score

92/100

Audited on May 11, 2025

No findings