Search among multiple models with ElasticSearch and Laravel Scout
Search among multiple models with ElasticSearch and Laravel Scout
Stay with Ukraine
UNITED24 launches the first fundraiser towards terrestrial robotic platforms. Squads of robots will save the lives of our military and civilians. They will become logistics devices, tow trucks, minelayers and deminers, as well as self-destructive robots. They will fight alongside people and for people.
The first robots are already proving their effectiveness on the battlefield. There will be more of them soon. Many more.
| Elasticsearch version | ElasticsearchDSL version |
|---|---|
| >= 8.0 | >= 8.0.0 |
| >= 7.0 | >= 3.0.0 |
| >= 6.0, [ |
// Other Service Providers
\Matchish\ScoutElasticSearch\ElasticSearchServiceProvider::class
],
Set `ELASTICSEARCH_HOST` env variableELASTICSEARCH_HOST=host:port
or use commas as separator for additional nodesELASTICSEARCH_HOST=host:port,host:port
You can disable SSL verification by setting the following in your envELASTICSEARCH_SSL_VERIFICATION=false
…php use Matchish\ScoutElasticSearch\Searchable\ImportSourceFactory; ... public function register(): void { $this->app->bind(ImportSourceFactory::class, MyImportSourceFactory::class);
Here is an example of `MyImportSourceFactory`
```php
namespace Matchish\ScoutElasticSearch\Searchable;
final class MyImportSourceFactory implements ImportSourceFactory
{
public static function from(string $className): ImportSource
{
//Add all required scopes
return new DefaultImportSource($className, [new WithCommentsScope()]);
}
}
class WithCommentsScope implements Scope {
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->with('comments');
}
}You can also customize your indexed data when you save models by leveraging the toSearchableArray method
provided by Laravel Scout through the Searchable trait
class Product extends Model
{
use Searchable;
/**
* Get the indexable data array for the model.
*
* @return array
*/
public function toSearchableArray()
{
$with = [
'categories',
];
$this->loadMissing($with);
return $this->toArray();
}
}
…
php
Product::search('(title:this OR description:this) AND (title:that OR description:that)')If it's not enough in your case you can pass a callback to the query builder
$results = Product::search('zonga', function(\Elastic\Elasticsearch\Client $client, $body) {
$minPriceAggregation = new MinAggregation('min_price');
$minPriceAggregation->setField('price');
$maxPriceAggregation = new MaxAggregation('max_price');
$maxPriceAggregation->setField('price');
$brandTermAggregation = new TermsAggregation('brand');
$brandTermAggregation->setField('brand');
$body->addAggregation($minPriceAggregation);
$body->addAggregation($brandTermAggregation);
return $client->search(['index' => 'products', 'body' => $body->toArray()])->asArray();
})->raw();
…
php
Product::search('(title:this OR description:this) AND (title:that OR description:that)')
->where('price', 100)
->whereIn('type', ['used', 'like new'])
->whereNotIn('type', ['new', 'refurbished']);Scout does not support any operators, but you can pass ElasticSearch terms like RangeQuery as value to ->where():
use ONGR\ElasticsearchDSL\Query\TermLevel\RangeQuery;
Product::search('(title:this OR description:this) AND (title:that OR description:that)')
->where('price', new RangeQuery('price', [
RangeQuery::GTE => 100,
RangeQuery::LTE => 1000,
]);And if you just want to search using RangeQuery without any query_string, you can call the search() method directly and leave the param empty.
use ONGR\ElasticsearchDSL\Query\TermLevel\RangeQuery;
Product::search()
->where('price', new RangeQuery('price', [
RangeQuery::GTE => 100,
]);
…
php
Product::search()
->take(20)
->options([
'from' => 20,
])
->paginate(50);This will return the first 50 results, ignoring the specified offset.
You can do it with MixedSearch class, just pass indices names separated by commas to the within method.
MixedSearch::search('title:Barcelona or to:Barcelona')
->within(implode(',', [
(new Ticket())->searchableAs(),
(new Book())->searchableAs(),
]))
->get();In this example you will get collection of Ticket and Book models where ticket's arrival city or
book title is Barcelona
Often your response isn't collection of models but aggregations or models with higlights and so on.
In this case you need to implement your own implementation of HitsIteratorAggregate and bind it in your service provider
Scout ElasticSearch is an open-sourced software licensed under the MIT license.
No open issues yet, or sync has not completed.