Skip to content

Instantly share code, notes, and snippets.

@thomasjsn
Created February 13, 2017 09:26
Show Gist options
  • Save thomasjsn/48185612dc7abe857b9a0ae5716b86c3 to your computer and use it in GitHub Desktop.
Save thomasjsn/48185612dc7abe857b9a0ae5716b86c3 to your computer and use it in GitHub Desktop.
Laravel console command for reindexing Elasticsearch.
<?php
namespace App\Console\Commands;
use Elasticsearch\ClientBuilder;
use Illuminate\Console\Command;
class ElasticRecreateIndex extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'elastic:reindex';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Recreate ElasticSearch index, with mapping, and reindex';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$host = config('scout.elasticsearch.hosts');
$index = config('scout.elasticsearch.index');
$client = ClientBuilder::create()->setHosts($host)->build();
if ($client->indices()->exists(['index' => $index])) {
$this->warn("Index {$index} exists, deleting...");
$client->indices()->delete(['index' => $index]);
}
$this->info("Creating index: {$index}");
$client->indices()->create([
'index' => $index,
'body' => [
"settings" => [
"number_of_shards" => 1,
"number_of_replicas" => 0,
"analysis" => [
"analyzer" => [
"synonym_filter" => [
"tokenizer" => "standard",
"filter" => ["lowercase", "synonym_filter"],
]
],
"filter" => [
"synonym_filter" => [
"type" => "synonym",
"synonyms_path" => "analysis/synonyms.txt",
]
]
]
]
]
]);
if ($this->confirm('Import all searchable models?')) {
$this->importPublic($client, $index);
}
}
/**
* @param $client
* @param $index
*/
private function importPublic($client, $index)
{
/*
|--------------------------------------------------------------------------
| Articles
|--------------------------------------------------------------------------
*/
$client->indices()->putMapping([
'index' => $index,
'type' => 'articles',
'body' => [
"_all" => [
"enabled" => true,
"analyzer" => "synonym_filter"
]
]
]);
$this->call('scout:import', ['model' => 'Your\Model']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment