2
0

CreateOpenSearchIndex.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Services\OpenSearchService;
  4. use Illuminate\Console\Command;
  5. class CreateOpenSearchIndex extends Command
  6. {
  7. /**
  8. * The name and signature of the console command.
  9. * php artisan create:opensearch.index
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'create:opensearch.index';
  14. /**
  15. * The console command description.
  16. *
  17. * @var string
  18. */
  19. protected $description = 'Command description';
  20. /**
  21. * Create a new command instance.
  22. *
  23. * @return void
  24. */
  25. public function __construct()
  26. {
  27. parent::__construct();
  28. }
  29. /**
  30. * Execute the console command.
  31. *
  32. * @return int
  33. */
  34. public function handle()
  35. {
  36. $openSearch = app(OpenSearchService::class);
  37. // Test OpenSearch connection
  38. $open = $openSearch->testConnection();
  39. if ($open[0]) {
  40. $this->info($open[1]);
  41. } else {
  42. $this->error($open[1]);
  43. return 1; // Exit with error code
  44. }
  45. // Attempt to create or update index
  46. try {
  47. $this->info('create openSearch index. index name='.config('mint.opensearch.index'));
  48. $crate = $openSearch->createIndex();
  49. if ($crate['acknowledged']) {
  50. $this->info('Index created successfully: '.$crate['index']);
  51. }
  52. if ($crate['shards_acknowledged']) {
  53. $this->info('Shards initialized successfully for index: '.$crate['index']);
  54. } else {
  55. $this->error('Shard initialization failed for index: '.$crate['index']);
  56. return 1;
  57. }
  58. } catch (\Exception $e) {
  59. if (str_contains($e->getMessage(), 'exists')) {
  60. $this->warn('Index already exists, attempting to update...');
  61. } else {
  62. $this->error('Failed to create index: '.$e->getMessage());
  63. }
  64. return 1;
  65. }
  66. return 0;
  67. }
  68. }