Skip to content

Instantly share code, notes, and snippets.

@demirhanali
Last active August 14, 2020 06:25
Show Gist options
  • Save demirhanali/e31de8858b32001a367ee6332e05c8b2 to your computer and use it in GitHub Desktop.
Save demirhanali/e31de8858b32001a367ee6332e05c8b2 to your computer and use it in GitHub Desktop.
<?php
namespace App\Scout;
use Elasticsearch\ClientBuilder;
use Laravel\Scout\Builder;
use Laravel\Scout\Engines\Engine;
/**
* Class ElasticEngine
* @package App\Scout
* @author Ali Cinci <[email protected]>
*/
class ElasticEngine extends Engine
{
/**
* @var Elastic
*/
protected $elastic;
/**
* Determines if soft deletes for Scout are enabled or not.
*
* @var bool
*/
protected $softDelete;
/**
* Create a new engine instance.
*
* @param false $softDelete
* @return void
*/
public function __construct($softDelete = false)
{
$elastic_ip = config('scout.elastic.connection.ip');
$elastic_port = config('scout.elastic.connection.port');
$host = [
"{$elastic_ip}:{$elastic_port}"
];
$elastic = ClientBuilder::create()
->setHosts($host)
->build();
$this->elastic = $elastic;
$this->softDelete = $softDelete;
}
/**
* @param \Illuminate\Database\Eloquent\Collection $models
*/
public function update($models) : void
{
$models->map(function ($model) {
$params = [
'index' => $model->searchableAs(),
'id' => $model->getScoutKey(),
'body' => [
'doc' => $model->toSearchableArray(),
'doc_as_upsert' => true
]
];
$this->elastic->index($params);
});
}
/**
* @param Builder $builder
* @param array $options
* @return mixed|void
*/
public function search(Builder $builder, array $options = [])
{
$params = [
'index' => $builder->index ?: $builder->model->searchableAs(),
'type' => '_doc',
'body' => [
'query' => [
'bool' => [
'must' => [['query_string' => [ 'query' => "*{$builder->query}*"]]]
]
]
]
];
return $this->elastic->search($params);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment