CreateOpenSearchIndex.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. $crate = $openSearch->createIndex();
  47. if ($crate['acknowledged']) {
  48. $this->info('Index created successfully: ' . $crate['index']);
  49. }
  50. if ($crate['shards_acknowledged']) {
  51. $this->info('Shards initialized successfully for index: ' . $crate['index']);
  52. } else {
  53. $this->error('Shard initialization failed for index: ' . $crate['index']);
  54. return 1;
  55. }
  56. } catch (\Exception $e) {
  57. if (str_contains($e->getMessage(), 'exists')) {
  58. $this->warn('Index already exists, attempting to update...');
  59. } else {
  60. $this->error('Failed to create index: ' . $e->getMessage());
  61. }
  62. return 1;
  63. }
  64. return 0;
  65. }
  66. }