2
0

CreateOpenSearchIndex.php 2.0 KB

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