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_'
]
]
]
];
}
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',
]
]
],
]
];
}
// 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();
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
]
]
];
}
}
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 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();
// 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;