CreateOpenSearchIndex.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. try {
  60. $update = $openSearch->updateIndex();
  61. if (!empty($update['settings']) && $update['settings']['acknowledged']) {
  62. $this->info('Index settings updated successfully');
  63. }
  64. if (!empty($update['mappings']) && $update['mappings']['acknowledged']) {
  65. $this->info('Index mappings updated successfully');
  66. }
  67. if (empty($update['settings']) && empty($update['mappings'])) {
  68. $this->warn('No settings or mappings provided for update');
  69. }
  70. } catch (\Exception $updateException) {
  71. $this->error('Failed to update index: ' . $updateException->getMessage());
  72. return 1;
  73. }
  74. } else {
  75. $this->error('Failed to create index: ' . $e->getMessage());
  76. return 1;
  77. }
  78. }
  79. return 0;
  80. }
  81. }