PHPackages                             ehsanhasani/elasticsearch - 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. ehsanhasani/elasticsearch

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

ehsanhasani/elasticsearch
=========================

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

1.3.1(8y ago)01501MITPHPPHP &gt;=5.6.6

Since Jan 7Pushed 8y ago1 watchersCompare

[ Source](https://github.com/ehsanhasani/elasticsearch)[ Packagist](https://packagist.org/packages/ehsanhasani/elasticsearch)[ Docs](http://basemkhirat.com)[ RSS](/packages/ehsanhasani-elasticsearch/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (5)Versions (39)Used By (0)

[![Build Status](https://camo.githubusercontent.com/0c4820fad911d208b3364b0534257c22538f1780236f02d1492c5d109bce6082/68747470733a2f2f7472617669732d63692e6f72672f626173656d6b68697261742f656c61737469637365617263682e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/basemkhirat/elasticsearch)[![Latest Stable Version](https://camo.githubusercontent.com/49048087a3344f9ced39a22ae4441ae7d38eb0a12607a6bbc3ce8286c172aa04/68747470733a2f2f706f7365722e707567782e6f72672f626173656d6b68697261742f656c61737469637365617263682f762f737461626c652e737667)](https://packagist.org/packages/basemkhirat/elasticsearch)[![Total Downloads](https://camo.githubusercontent.com/2770da5b4fb00d470abd114c7f843f9b248f3c3c9ce036b6d43f2b384b3204b2/68747470733a2f2f706f7365722e707567782e6f72672f626173656d6b68697261742f656c61737469637365617263682f642f746f74616c2e737667)](https://packagist.org/packages/basemkhirat/elasticsearch)[![License](https://camo.githubusercontent.com/500de42ba5f92a41901d0e5fb855ae7875094c0a2cfbcf9ae19185ae5fac7244/68747470733a2f2f706f7365722e707567782e6f72672f626173656d6b68697261742f656c61737469637365617263682f6c6963656e73652e737667)](https://packagist.org/packages/basemkhirat/elasticsearch)

[![](https://camo.githubusercontent.com/7c262f60a909781dde148fc187710549be91b80f99e403314bc0e8aa95855773/687474703a2f2f626173656d6b68697261742e636f6d2f696d616765732f626173656d6b68697261742d656c61737469637365617263682e706e673f313233)](https://camo.githubusercontent.com/7c262f60a909781dde148fc187710549be91b80f99e403314bc0e8aa95855773/687474703a2f2f626173656d6b68697261742e636f6d2f696d616765732f626173656d6b68697261742d656c61737469637365617263682e706e673f313233)

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

[](#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](https://laravel.com/docs/5.4/scout) driver.
- Dealing with multiple elasticsearch connections at the same time.
- Awesome pagination based on [LengthAwarePagination](https://github.com/illuminate/pagination).
- Caching queries using a caching layer over query builder built on [laravel cache](https://laravel.com/docs/5.4/cache).

Requirements
------------

[](#requirements)

- `php` &gt;= 5.6.6

    See [Travis CI Builds](https://travis-ci.org/basemkhirat/elasticsearch).
- `laravel/laravel` &gt;= 5.\* or `laravel/lumen` &gt;= 5.\* or `composer application`

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

[](#documentation)

See [Full Documentation](https://github.com/basemkhirat/elasticsearch/wiki/1.-Installation).

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

[](#installation)

### Laravel Installation

[](#laravel-installation)

##### 1) Install package using composer.

[](#1-install-package-using-composer)

```
$ composer require basemkhirat/elasticsearch
```

##### 2) Add package service provider (&lt; laravel 5.5).

[](#2-add-package-service-provider--laravel-55)

```
Basemkhirat\Elasticsearch\ElasticsearchServiceProvider::class
```

##### 3) Add package alias (&lt; laravel 5.5).

[](#3-add-package-alias--laravel-55)

```
'ES' => Basemkhirat\Elasticsearch\Facades\ES::class
```

##### 4) Publishing.

[](#4-publishing)

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

### Lumen Installation

[](#lumen-installation)

##### 1) Install package using composer.

[](#1-install-package-using-composer-1)

```
$ composer require basemkhirat/elasticsearch
```

##### 2) Add package service provider in `bootstrap/app.php`.

[](#2-add-package-service-provider-in-bootstrapappphp)

```
$app->register(Basemkhirat\Elasticsearch\ElasticsearchServiceProvider::class);
```

##### 3) Copy package config directory `vendor/basemkhirat/elasticsearch/src/config` to root folder alongside with `app` directory.

[](#3-copy-package-config-directory-vendorbasemkhiratelasticsearchsrcconfig-to-root-folder-alongside-with-app-directory)

##### 4) Making Lumen work with facades by uncommenting this line in `bootstrap/app.php`.

[](#4-making-lumen-work-with-facades-by-uncommenting-this-line-in-bootstrapappphp)

```
$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();
```

### Composer Installation

[](#composer-installation)

You can install package with any composer-based applications

##### 1) Install package using composer.

[](#1-install-package-using-composer-2)

```
$ composer require basemkhirat/elasticsearch
```

##### 2) Creating a connection.

[](#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',
]);

# access the query builder using created connection

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

Configuration (Laravel &amp; Lumen)
-----------------------------------

[](#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 &amp; Lumen)
------------------------------------------------------

[](#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

[](#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

[](#create-indices-defined-in-esphp-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

[](#update-indices-defined-in-esphp-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

[](#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)

[](#reindexing-data-with-zero-downtime)

##### First, why reindexing?

[](#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:

[](#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"
]
```

2. Update index with command:

```
$ php artisan es:indices:update my_index
```

3. Create a new index as example `my_new_index` with your new mapping in configuration file.

```
$ php artisan es:indices:create my_new_index
```

4. 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
```

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

[](#usage-as-a-laravel-scout-driver)

First, follow [Laravel Scout installation](https://laravel.com/docs/5.4/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](https://laravel.com/docs/5.4/scout#configuration).

Elasticsearch data model
------------------------

[](#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

[](#basic-usage)

```
