1
|
|
|
<?php |
|
|
|
|
2
|
|
|
namespace Triadev\Leopard\Console\Commands\Index; |
|
|
|
|
3
|
|
|
|
4
|
|
|
use Illuminate\Console\Command; |
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
6
|
|
|
use Illuminate\Support\Collection; |
7
|
|
|
use Triadev\Leopard\Business\Helper\IsModelSearchable; |
8
|
|
|
use Triadev\Leopard\Facade\Leopard; |
9
|
|
|
use Triadev\Leopard\Searchable; |
10
|
|
|
|
11
|
|
|
class Sync extends Command |
|
|
|
|
12
|
|
|
{ |
|
|
|
|
13
|
|
|
use IsModelSearchable; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* The console command name. |
17
|
|
|
* |
18
|
|
|
* @var string |
19
|
|
|
*/ |
20
|
|
|
protected $signature = 'triadev:index:sync {--index=}'; |
|
|
|
|
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* The console command description. |
24
|
|
|
* |
25
|
|
|
* @var string |
26
|
|
|
*/ |
27
|
|
|
protected $description = 'Sync the elasticsearch index with persist data.'; |
|
|
|
|
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Execute the console command. |
31
|
|
|
*/ |
|
|
|
|
32
|
2 |
|
public function handle() |
|
|
|
|
33
|
|
|
{ |
34
|
2 |
|
$index = $this->option('index') ?: Leopard::getEsDefaultIndex(); |
|
|
|
|
35
|
|
|
|
36
|
2 |
|
if (!Leopard::getEsClient()->indices()->exists(['index' => $index])) { |
|
|
|
|
37
|
1 |
|
$this->error(sprintf("The index does not exist: %s", $index)); |
|
|
|
|
38
|
1 |
|
return; |
39
|
|
|
} |
40
|
|
|
|
41
|
1 |
|
$chunkSize = $this->getChunkSize(); |
42
|
|
|
|
43
|
1 |
|
foreach ($this->getModelsToSync($index) as $modelClass => $model) { |
44
|
1 |
|
$this->line(sprintf("Sync index with model: %s", $modelClass)); |
|
|
|
|
45
|
|
|
|
46
|
|
|
$model::chunk($chunkSize, function ($models) { |
|
|
|
|
47
|
|
|
/** @var Collection $models */ |
|
|
|
|
48
|
1 |
|
Leopard::repository()->bulkSave($models); |
49
|
1 |
|
$this->line(sprintf("Indexing a chunk of %s documents ...", count($models))); |
|
|
|
|
50
|
1 |
|
}); |
|
|
|
|
51
|
|
|
} |
52
|
1 |
|
} |
|
|
|
|
53
|
|
|
|
54
|
|
|
/** |
|
|
|
|
55
|
|
|
* @return int |
|
|
|
|
56
|
|
|
*/ |
57
|
1 |
|
private function getChunkSize() : int |
|
|
|
|
58
|
|
|
{ |
59
|
1 |
|
return config('leopard.sync.chunkSize'); |
60
|
|
|
} |
|
|
|
|
61
|
|
|
|
62
|
|
|
/** |
|
|
|
|
63
|
|
|
* @param string $index |
|
|
|
|
64
|
|
|
* @return Model|Searchable[] |
65
|
|
|
*/ |
66
|
1 |
|
private function getModelsToSync(string $index) : array |
|
|
|
|
67
|
|
|
{ |
68
|
1 |
|
$models = []; |
69
|
|
|
|
70
|
1 |
|
foreach (config(sprintf("leopard.sync.models.%s", $index), []) as $modelClass) { |
|
|
|
|
71
|
|
|
/** @var Model|Searchable $model */ |
|
|
|
|
72
|
1 |
|
$model = new $modelClass(); |
73
|
|
|
|
74
|
1 |
|
$this->isModelSearchable($model); |
|
|
|
|
75
|
|
|
|
76
|
1 |
|
$models[$modelClass] = $model; |
77
|
|
|
} |
78
|
|
|
|
79
|
1 |
|
return $models; |
80
|
|
|
} |
|
|
|
|
81
|
|
|
} |
|
|
|
|
82
|
|
|
|