diff --git a/src/Console/Commands/ReImportCommand.php b/src/Console/Commands/ReImportCommand.php index 53e80140..60fede66 100644 --- a/src/Console/Commands/ReImportCommand.php +++ b/src/Console/Commands/ReImportCommand.php @@ -88,16 +88,25 @@ public function handle( $temporaryIndex = $client->initIndex($temporaryName); - try { - $temporaryIndex->getSettings(); - - $response = $client->moveIndex($temporaryName, $index->getIndexName()); + $hits = (int) $temporaryIndex->search('')['nbHits']; + if ($hits === 0) { + $response = $index->clearObjects(); if ($config->get('scout.synchronous', false)) { $response->wait(); } - } catch (NotFoundException $e) { - $index->setSettings(['attributesForFaceting' => null])->wait(); + } else { + try { + $temporaryIndex->getSettings(); + + $response = $client->moveIndex($temporaryName, $index->getIndexName()); + + if ($config->get('scout.synchronous', false)) { + $response->wait(); + } + } catch (NotFoundException $e) { + $index->setSettings(['attributesForFaceting' => null])->wait(); + } } } diff --git a/tests/Features/ReimportCommandTest.php b/tests/Features/ReimportCommandTest.php index 7d083a7c..5fbef982 100644 --- a/tests/Features/ReimportCommandTest.php +++ b/tests/Features/ReimportCommandTest.php @@ -40,4 +40,31 @@ public function testReimport(): void Artisan::call('scout:reimport', ['searchable' => User::class]); } + + public function testEmptyReimport(): void + { + factory(User::class, 0)->create(); + + $client = $this->mockClient(); + + $userIndex = $this->mockIndex(User::class); + + $userTemporaryIndex = $this->mockIndex('temp_'.(new User())->searchableAs()); + + $client->shouldReceive('copyIndex')->with((new User())->searchableAs(), $userTemporaryIndex->getIndexName(), [ + 'scope' => [ + 'settings', + 'synonyms', + 'rules', + ], + ])->andReturn($this->mockResponse()); + + $userTemporaryIndex->shouldReceive('search')->andReturn(['nbHits' => 0]); + + $userIndex->shouldReceive('clearObjects')->andReturn(['nbHits' => 0]); + + $client->shouldReceive('clearObjects')->andReturn($this->mockResponse()); + + Artisan::call('scout:reimport', ['searchable' => User::class]); + } }