This package offers advanced functionality for searching and filtering data in Elasticsearch.Check out its features!
The package has been tested in the following configuration:
Use composer to install the package:
composer require babenkoivan/scout-elasticsearch-driver
If you are using Laravel version <= 5.4 or the package discoveryis disabled, add the following providers in config/app.php
:
'providers' => [
Laravel\Scout\ScoutServiceProvider::class,
ScoutElastic\ScoutElasticServiceProvider::class,
]
To configure the package you need to publish settings first:
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
php artisan vendor:publish --provider="ScoutElastic\ScoutElasticServiceProvider"
Then, set the driver setting to elastic
in the config/scout.php
file (or set SCOUT_DRIVER=elastic
in the .env
) and configure the driver itself in the config/scout_elastic.php
file.The available options are:
Option | Description |
---|---|
client | A setting hash to build Elasticsearch client. More information you can find here. By default the host is set to localhost:9200 . |
update_mapping | The option that specifies whether to update a mapping automatically or not. By default it is set to true . |
indexer | Set to single for the single document indexing and to bulk for the bulk document indexing. By default is set to single . |
document_refresh | This option controls when updated documents appear in the search results. Can be set to 'true' , 'false' , 'wait_for' or null . More details about this option you can find here. By default set to null . |
Note, that if you use the bulk document indexing you'll probably want to change the chunk size, you can do that in the config/scout.php
file.
An index configurator class is used to set up settings for an Elasticsearch index.To create a new index configurator use the following artisan command:
php artisan make:index-configurator MyIndexConfigurator
It'll create the file MyIndexConfigurator.php
in the app
folder of your project.You can specify index name and settings like in the following example:
<?php
namespace App;
use ScoutElastic\IndexConfigurator;
class MyIndexConfigurator extends IndexConfigurator
{
// It's not obligatory to determine name. By default it'll be a snaked class name without `IndexConfigurator` part.
protected $name = 'my_index';
// You can specify any settings you want, for example, analyzers.
protected $settings = [
'analysis' => [
'analyzer' => [
'es_std' => [
'type' => 'standard',
'stopwords' => '_spanish_'
]
]
]
];
}
More about index settings you can find in the index management section of Elasticsearch documentation.
To create an index just run the artisan command:
php artisan elastic:create-index "App\MyIndexConfigurator"
Note, that every searchable model requires its own index configurator.
Indices created in Elasticsearch 6.0.0 or later may only contain a single mapping type. Indices created in 5.x with multiple mapping types will continue to function as before in Elasticsearch 6.x. Mapping types will be completely removed in Elasticsearch 7.0.0.
You can find more information here.
To create a model with the ability to perform search requests in an Elasticsearch index use the command:
php artisan make:searchable-model MyModel --index-configurator=MyIndexConfigurator
After executing the command you'll find the file MyModel.php
in you app
folder:
<?php
namespace App;
use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
use Searchable;
protected $indexConfigurator = MyIndexConfigurator::class;
protected $searchRules = [
//
];
// Here you can specify a mapping for model fields
protected $mapping = [
'properties' => [
'title' => [
'type' => 'text',
// Also you can configure multi-fields, more details you can find here https://www.elastic.co/guide/en/elasticsearch/reference/current/multi-fields.html
'fields' => [
'raw' => [
'type' => 'keyword',
]
]
],
]
];
}
Each searchable model represents an Elasticsearch type.By default a type name is the same as a table name, but you can set any type name you want through the searchableAs
method.You can also specify fields which will be indexed by the driver through the toSearchableArray
method.More information about these options you will find in the scout official documentation.
The last important option you can set in the MyModel
class is the $searchRules
property.It allows you to set different search algorithms for a model.We'll take a closer look at it in the search rules section.
After setting up a mapping in your model you can update an Elasticsearch type mapping:
php artisan elastic:update-mapping "App\MyModel"
Once you've created an index configurator, an Elasticsearch index itself and a searchable model, you are ready to go.Now you can index and search data according to the documentation.
Basic search usage example:
// set query string
App\MyModel::search('phone')
// specify columns to select
->select(['title', 'price'])
// filter
->where('color', 'red')
// sort
->orderBy('price', 'asc')
// collapse by field
->collapse('brand')
// set offset
->from(0)
// set limit
->take(10)
// get results
->get();
If you only need the number of matches for a query, use the count
method:
App\MyModel::search('phone')
->count();
If you need to load relations, use the with
method:
App\MyModel::search('phone')
->with('makers')
->get();
In addition to standard functionality the package offers you the possibility to filter data in Elasticsearch without specifying a query string:
App\MyModel::search('*')
->where('id', 1)
->get();
Also you can override model search rules:
App\MyModel::search('Brazil')
->rule(App\MySearchRule::class)
->get();
And use variety of where
conditions:
App\MyModel::search('*')
->whereRegexp('name.raw', 'A.+')
->where('age', '>=', 30)
->whereExists('unemployed')
->get();
And filter out results with a score less than min_score:
App\MyModel::search('sales')
->minScore(1.0)
->get();
And add more complex sorting (geo_distance eg.)
$model = App\MyModel::search('sales')
->orderRaw([
'_geo_distance' => [
'coordinates' => [
'lat' => 51.507351,
'lon' => -0.127758
],
'order' => 'asc',
'unit' => 'm'
]
])
->get();
// To retrieve sort result, use model `sortPayload` attribute:
$model->sortPayload;
At last, if you want to send a custom request, you can use the searchRaw
method:
App\MyModel::searchRaw([
'query' => [
'bool' => [
'must' => [
'match' => [
'_all' => 'Brazil'
]
]
]
]
]);
This query will return raw response.
Available artisan commands are listed below:
Command | Arguments | Description |
---|---|---|
make:index-configurator | name - The name of the class |
Creates a new Elasticsearch index configurator. |
make:searchable-model | name - The name of the class |
Creates a new searchable model. |
make:search-rule | name - The name of the class |
Creates a new search rule. |
elastic:create-index | index-configurator - The index configurator class |
Creates an Elasticsearch index. |
elastic:update-index | index-configurator - The index configurator class |
Updates settings and mappings of an Elasticsearch index. |
elastic:drop-index | index-configurator - The index configurator class |
Drops an Elasticsearch index. |
elastic:update-mapping | model - The model class |
Updates a model mapping. |
elastic:migrate-model | model - The model class, target-index - The index name to migrate |
Migrates model to another index. |
For detailed description and all available options run php artisan help [command]
in the command line.
A search rule is a class that describes how a search query will be executed.To create a search rule use the command:
php artisan make:search-rule MySearchRule
In the file app/MySearchRule.php
you will find a class definition:
<?php
namespace App;
use ScoutElastic\SearchRule;
class MySearch extends SearchRule
{
// This method returns an array, describes how to highlight the results.
// If null is returned, no highlighting will be used.
public function buildHighlightPayload()
{
return [
'fields' => [
'name' => [
'type' => 'plain'
]
]
];
}
// This method returns an array, that represents bool query.
public function buildQueryPayload()
{
return [
'must' => [
'match' => [
'name' => $this->builder->query
]
]
];
}
}
You can read more about bool queries hereand about highlighting here.
The default search rule returns the following payload:
return [
'must' => [
'query_string' => [
'query' => $this->builder->query
]
]
];
This means that by default when you call search
method on a model it tries to find the query string in any field.
To determine default search rules for a model just add a property:
<?php
namespace App;
use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
use Searchable;
// You can set several rules for one model. In this case, the first not empty result will be returned.
protected $searchRules = [
MySearchRule::class
];
}
You can also set a search rule in a query builder:
// You can set either a SearchRule class
App\MyModel::search('Brazil')
->rule(App\MySearchRule::class)
->get();
// or a callable
App\MyModel::search('Brazil')
->rule(function($builder) {
return [
'must' => [
'match' => [
'Country' => $builder->query
]
]
];
})
->get();
To retrieve highlight, use model highlight
attribute:
// Let's say we highlight field `name` of `MyModel`.
$model = App\MyModel::search('Brazil')
->rule(App\MySearchRule::class)
->first();
// Now you can get raw highlighted value:
$model->highlight->name;
// or string value:
$model->highlight->nameAsString;
You can use different types of filters:
Method | Example | Description |
---|---|---|
where($field, $value) | where('id', 1) | Checks equality to a simple value. |
where($field, $operator, $value) | where('id', '>=', 1) | Filters records according to a given rule. Available operators are: =, <, >, <=, >=, <>. |
whereIn($field, $value) | whereIn('id', [1, 2, 3]) | Checks if a value is in a set of values. |
whereNotIn($field, $value) | whereNotIn('id', [1, 2, 3]) | Checks if a value isn't in a set of values. |
whereBetween($field, $value) | whereBetween('price', [100, 200]) | Checks if a value is in a range. |
whereNotBetween($field, $value) | whereNotBetween('price', [100, 200]) | Checks if a value isn't in a range. |
whereExists($field) | whereExists('unemployed') | Checks if a value is defined. |
whereNotExists($field) | whereNotExists('unemployed') | Checks if a value isn't defined. |
whereMatch($field, $value) | whereMatch('tags', 'travel') | Filters records matching exact value. Here you can find more about syntax. |
whereNotMatch($field, $value) | whereNotMatch('tags', 'travel') | Filters records not matching exact value. Here you can find more about syntax. |
whereRegexp($field, $value, $flags = 'ALL') | whereRegexp('name.raw', 'A.+') | Filters records according to a given regular expression. Here you can find more about syntax. |
whereGeoDistance($field, $value, $distance) | whereGeoDistance('location', [-70, 40], '1000m') | Filters records according to given point and distance from it. Here you can find more about syntax. |
whereGeoBoundingBox($field, array $value) | whereGeoBoundingBox('location', ['top_left' => [-74.1, 40.73], 'bottom_right' => [-71.12, 40.01]]) | Filters records within given boundings. Here you can find more about syntax. |
whereGeoPolygon($field, array $points) | whereGeoPolygon('location', [[-70, 40],[-80, 30],[-90, 20]]) | Filters records within given polygon. Here you can find more about syntax. |
whereGeoShape($field, array $shape, $relation = 'INTERSECTS') | whereGeoShape('shape', ['type' => 'circle', 'radius' => '1km', 'coordinates' => [4, 52]], 'WITHIN') | Filters records within given shape. Here you can find more about syntax. |
In most cases it's better to use raw fields to filter records, i.e. not analyzed fields.
As you might know, you can't change the type of already created field in Elasticsearch.The only choice in such case is to create a new index with necessary mapping and import your models into the new index.
A migration can take quite a long time, so to avoid downtime during the process the driver reads from the old index and writes to the new one.As soon as migration is over it starts reading from the new index and removes the old index.This is how the artisan elastic:migrate-model
command works.
Before you run the command, make sure that your index configurator uses the ScoutElastic\Migratable
trait.If it's not, add the trait and run the artisan elastic:update-index
command using your index configurator class name as an argument:
php artisan elastic:update-index "App\MyIndexConfigurator"
When you are ready, make changes in the model mapping and run the elastic:migrate-model
command using the model class as the first argument and desired index name as the second argument:
php artisan elastic:migrate-model "App\MyModel" my_index_v2
Note, that if you need just to add new fields in your mapping, use the elastic:update-mapping
command.
There are two methods that can help you to analyze results of a search query:
App\MyModel::search('Brazil')
->explain();
App\MyModel::search('Brazil')
->profile();
Both methods return raw data from ES.
Besides, you can get a query payload that will be sent to ES, by calling the buildPayload
method.
App\MyModel::search('Brazil')
->buildPayload();
Note, that this method returns a collection of payloads, because of possibility of using multiple search rules in one query.
Recently I've released a new Elasticsearch ecosystem for Laravel, it includes:
If any of it sounds interesting to you and you want to get more details, please readThe Ultimate Guide to Elasticsearch in Laravel Application.The article makes a good overview of the mentioned packages and provides usage examples.
FAQ:
scout-elasticsearch-driver
version? - I didn't want to create anotherall in one package for obvious reasons: no separation of concerns, not compatible with other Scout drivers, hard to testand develop, etc. As Elastic Scout Driver is a generic driver and doesn't implement all the scout-elasticsearch-driver
features, it would be wrong to call it a new scout-elasticsearch-driver
version.scout-elasticsearch-driver
in the future.项目地址:https://github.com/yb19890724/laravel-es 1。在本地穿件数据库,修改.env 的信息 我的env文件点击下载 2。env中配置es 的地址。 3.根目录下执行 composer update php artisan laraveles npm install npm run dev 查看es 中是否有producs之类的数据,查看方式: htt
一 简介 laravel 的组件化使 laravel 的使用更加得心应手。 Laravel Scout 为 Eloquent 模型 全文搜索提供了简单的,基于驱动的解决方案。通过使用模型观察者,Scout 会自动同步 Eloquent 记录的搜索索引。 简单的来说 Scout 是用来全文检索的一个组件(不具有搜索功能),它使用驱动来调用搜索引擎来进行搜索。这里讲解 laravel 使用 e
环境要求 laravel 5.5 elasticsearch服务器一台 【服务器搭建,请看https://blog.csdn.net/zhazhaji/article/details/83508120】 文档: laravel的scout文档 https://laravel.com/docs/5.5/scout elasticseartch文档 https://www.elastic.co/gui
写在前面 Elasticsearch(以下简称es)是一个实时的分布式搜索和分析引擎。 在搜索引擎方面,不仅仅有Elasticsearch,像另一篇提到的Algolia,还有sphinx、Solr等等,这里不做评价和比较,本篇主要介绍laravel中如何使用Elasticsearch。 首选必须安装有Elasticsearch,请参考 https://www.tech1024.cn/origina
1、首先安装 jave环境 jdk 下载地址 ,我用的是最新版本的,有时版本要跟elasticsearch对应 2、安装elasticsearch 下载地址 3、安装Laravel scout 全文搜索包,这里我用的是5.0.3版本,tamayo/laravel-scout-elastic .这里的版本很重要,不然一会就出错了! composer require laravel/scout=5.0
安装需要的组件 composer require tamayo/laravel-scout-elastic composer require laravel/scout 如果composer require laravel/scout 出现报错 Using version ^6.1 for laravel/scout ./composer.json has been updated Loading
1.laravel-scout扩展包的安装 composer require laravel/scout 会下载到laravel框架的vendor/laravle/scout目录下 2.在config/app.php配置providers 数组中:添加scout服务提供者 Laravel\Scout\ScoutServiceProvider::class, 3.注册好 Scout 的服务提供者之后
1、elasticsearch安装 前提条件:必须安装jdk 安装 elasticsearch——composer require elasticsearch 2、scout安装 如果laravel版本是5.8则 1、运行 composer reuqire laravel/scout ^6.0 2、在config/app.php配置文件中的providers数组加入: Laravel\Scou
我做了一个导航站(域名是挂路灯的全拼gualudeng.com),里面精选了各种影视,动漫,黑科技,实用工具,搞笑有趣的站点,动动大家可爱的小手,点进来看看吧,良心站点。 1.安装相应插件 composer require elasticsearch/elasticsearch composer require laravel/scout composer require matchish/lar
scout is a RESTful search serverwritten in Python. The search is powered by SQLite's full-text search extension,and the web application utilizes the Flask framework. Scout aims to be a lightweight, RE
简介 Laravel Scout 为 Eloquent 模型 全文搜索提供了简单的,基于驱动的解决方案。通过使用模型观察者,Scout 会自动同步 Eloquent 记录的搜索索引。 目前,Scout 自带一个 Algolia 驱动;不过,编写自定义驱动很简单, 你可以轻松的通过自己的搜索实现来扩展 Scout。 安装 首先,通过 Composer 包管理器来安装 Scout: composer
Apache Scout 旨在实现 Java API for XML Registries (JAXR) 协议的Java类库,可以使用它来与 UDDI 注册中心通讯。
TNTSearch Driver for Laravel Scout - Laravel 5.3 - 8.0 This package makes it easy to add full text search support to your models with Laravel 5.3 to 8.0. Premium products If you find TNT Search to be
Laravel Scout Elasticsearch Driver This package provides a Elasticsearch driver for Laravel Scout. Contents Installation Usage Credits License Installation You can install the package via composer: co
本文向大家介绍Laravel使用scout集成elasticsearch做全文搜索的实现方法,包括了Laravel使用scout集成elasticsearch做全文搜索的实现方法的使用技巧和注意事项,需要的朋友参考一下 本文介绍了Laravel使用scout集成elasticsearch做全文搜索的实现方法,分享给大家,具体如下: 安装需要的组件 如果composer require larave