eloquent-search
, (*1)
Index Eloquent models to Elasticsearch. Eloquent-search use Official low-level client for Elasticsearch.
You should read more about Elasticsearch at https://www.elastic.co to get basic knowledge., (*2)
Installation via Composer
The recommended method to install eloquent-search is through Composer., (*3)
composer require thaoha/eloquent-search
Once you've run a composer update, you need to register Laravel service provider, in your config/app.php:, (*4)
'providers' => [
...
EloquentEs\EloquentEsServiceProvider::class,
],
Or with Lumen, you need add to bootstrap/app.php:, (*5)
$app->register(EloquentEs\EloquentEsServiceProvider::class);
And now you can add ElasticModelTrait to any Eloquent model you want to index to Elasticsearch:, (*6)
use EloquentEs\Supports\ElasticModelTrait;
/**
* Class Company
* @package App\Models
*/
class Company extends Model
{
use ElasticModelTrait;
...
}
Config
Laravel 5:, (*7)
$ php artisan vendor:publish --provider="EloquentEs\EloquentEsServiceProvider"
Or you can copy config.php file to your config folder and change the filename to elastic.php. With Lumen you need add new config file to bootstrap/app:, (*8)
$app->configure('elastic');
Index
Create index to store your data first. Use esCreateIndex() function from you model class:, (*9)
App\Models\Company::esCreateIndex();
esCreateIndex() function use property $esIndexMapping in Company model to set mapping settings. Elastic will auto detect if $esIndexMapping empty:, (*10)
/**
* Index mapping
*
* @var array
*/
private $esIndexMapping = [
'id' => ['type' => 'long'],
'name' => ['type' => 'string'],
'company' => ['type' => 'string']
];
If you want to update mapping settings you can use (use esReset() function when conflict error):, (*11)
App\Models\Company::esPutMapping();
Delete index:, (*12)
App\Models\Company::esDeleteIndex();
Reset index. Just use this function (this function will delete all your index include your data and create new one with mapping settings):, (*13)
App\Models\Company::esReset();
Get and Index model
With each model object already use ElasticModelTrait you can index to Elasticsearch with esIndex() function:, (*14)
$company = App\Models\Company::find(1);
$company->esIndex();
With default it will be use $company->toArray() to get data. Very easy to override with esSerialize() function:, (*15)
/**
* Get eloquent model data
*
* @return array
*/
public function esSerialize()
{
$data = $this->toArray();
$data['user_id'] = 1;
return $data;
}
Delete model
$company = App\Models\Company::find(1);
$company->esDelete();
Update model
$company = App\Models\Company::find(1);
$company->esReindex();
a Model or a Collection you can do with same way., (*16)
Search
$params = [
'match' => ['name' => 'keyword']
];
$hits = App\Models\Company::esSearch($params);
You should read more at https://www.elastic.co/ to build you params search, (*17)