Skip to content

Add SettingsUpdater service #317

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions config/services.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@
</service>
<service id="Meilisearch\Bundle\SearchService" alias="meilisearch.service" />

<service id="meilisearch.settings_updater" class="Meilisearch\Bundle\Services\SettingsUpdater">
<argument type="service" id="meilisearch.service" />
<argument type="service" id="meilisearch.client" />
<argument type="service" id="event_dispatcher" />
</service>
<service id="Meilisearch\Bundle\Services\SettingsUpdater" alias="meilisearch.settings_updater" />

<service id="Meilisearch\Bundle\Command\MeilisearchClearCommand">
<argument type="service" id="meilisearch.service" />
<tag name="console.command" />
Expand All @@ -52,6 +59,8 @@
<service id="Meilisearch\Bundle\Command\MeilisearchCreateCommand">
<argument type="service" id="meilisearch.service" />
<argument type="service" id="meilisearch.client" />
<argument type="service" id="meilisearch.settings_updater" />
<argument type="service" id="event_dispatcher" />
<tag name="console.command" />
</service>

Expand All @@ -64,6 +73,8 @@
<argument type="service" id="meilisearch.service" />
<argument type="service" id="doctrine" />
<argument type="service" id="meilisearch.client" />
<argument type="service" id="meilisearch.settings_updater" />
<argument type="service" id="event_dispatcher" />
<tag name="console.command" />
</service>

Expand Down
5 changes: 4 additions & 1 deletion src/Command/IndexCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,12 @@

abstract class IndexCommand extends Command
{
private string $prefix;
protected const DEFAULT_RESPONSE_TIMEOUT = 5000;

protected SearchService $searchService;

private string $prefix;

public function __construct(SearchService $searchService)
{
$this->searchService = $searchService;
Expand Down
105 changes: 53 additions & 52 deletions src/Command/MeilisearchCreateCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,30 @@
namespace Meilisearch\Bundle\Command;

use Meilisearch\Bundle\Collection;
use Meilisearch\Bundle\Exception\InvalidSettingName;
use Meilisearch\Bundle\Exception\TaskException;
use Meilisearch\Bundle\EventListener\ConsoleOutputSubscriber;
use Meilisearch\Bundle\Model\Aggregator;
use Meilisearch\Bundle\SearchService;
use Meilisearch\Bundle\SettingsProvider;
use Meilisearch\Bundle\Services\SettingsUpdater;
use Meilisearch\Client;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

final class MeilisearchCreateCommand extends IndexCommand
{
private Client $searchClient;
private SettingsUpdater $settingsUpdater;
private EventDispatcherInterface $eventDispatcher;

public function __construct(SearchService $searchService, Client $searchClient)
public function __construct(SearchService $searchService, Client $searchClient, SettingsUpdater $settingsUpdater, EventDispatcherInterface $eventDispatcher)
{
parent::__construct($searchService);

$this->searchClient = $searchClient;
$this->settingsUpdater = $settingsUpdater;
$this->eventDispatcher = $eventDispatcher;
}

public static function getDefaultName(): string
Expand All @@ -40,33 +45,32 @@ protected function configure(): void
{
$this
->setDescription(self::getDefaultDescription())
->addOption('indices', 'i', InputOption::VALUE_OPTIONAL, 'Comma-separated list of index names');
}

private function entitiesToIndex($indexes): array
{
foreach ($indexes as $key => $index) {
$entityClassName = $index['class'];
if (is_subclass_of($entityClassName, Aggregator::class)) {
$indexes->forget($key);

$indexes = new Collection(array_merge(
$indexes->all(),
array_map(
static fn ($entity) => ['name' => $index['name'], 'class' => $entity],
$entityClassName::getEntities()
)
));
}
}

return array_unique($indexes->all(), SORT_REGULAR);
->addOption('indices', 'i', InputOption::VALUE_OPTIONAL, 'Comma-separated list of index names')
->addOption(
'update-settings',
null,
InputOption::VALUE_NEGATABLE,
'Update settings related to indices to the search engine',
true
)
->addOption(
'response-timeout',
't',
InputOption::VALUE_REQUIRED,
'Timeout (in ms) to get response from the search engine',
self::DEFAULT_RESPONSE_TIMEOUT
)
;
}

protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->eventDispatcher->addSubscriber(new ConsoleOutputSubscriber(new SymfonyStyle($input, $output)));

$indexes = $this->getEntitiesFromArgs($input, $output);
$entitiesToIndex = $this->entitiesToIndex($indexes);
$updateSettings = $input->getOption('update-settings');
$responseTimeout = ((int) $input->getOption('response-timeout')) ?: self::DEFAULT_RESPONSE_TIMEOUT;

/** @var array $index */
foreach ($entitiesToIndex as $index) {
Expand All @@ -79,41 +83,38 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$output->writeln('<info>Creating index '.$index['name'].' for '.$entityClassName.'</info>');

$task = $this->searchClient->createIndex($index['name']);
$this->searchClient->waitForTask($task['taskUid']);
$indexInstance = $this->searchClient->index($index['name']);
$this->searchClient->waitForTask($task['taskUid'], $responseTimeout);

if (isset($index['settings']) && is_array($index['settings'])) {
foreach ($index['settings'] as $variable => $value) {
$method = sprintf('update%s', ucfirst($variable));
if ($updateSettings) {
$this->settingsUpdater->update($index['name'], $responseTimeout);
}
}

if (!method_exists($indexInstance, $method)) {
throw new InvalidSettingName(sprintf('Invalid setting name: "%s"', $variable));
}
$output->writeln('<info>Done!</info>');

if (isset($value['_service']) && $value['_service'] instanceof SettingsProvider) {
$value = $value['_service']();
} elseif ('distinctAttribute' === $variable && is_array($value)) {
$value = $value[0] ?? null;
}
return 0;
}

// Update
$task = $indexInstance->{$method}($value);
private function entitiesToIndex($indexes): array
{
foreach ($indexes as $key => $index) {
$entityClassName = $index['class'];

// Get task information using uid
$indexInstance->waitForTask($task['taskUid']);
$task = $indexInstance->getTask($task['taskUid']);
if (!is_subclass_of($entityClassName, Aggregator::class)) {
continue;
}

if ('failed' === $task['status']) {
throw new TaskException($task['error']);
}
$indexes->forget($key);

$output->writeln('<info>Settings updated of "'.$index['name'].'".</info>');
}
}
$indexes = new Collection(array_merge(
$indexes->all(),
array_map(
static fn ($entity) => ['name' => $index['name'], 'prefixed_name' => $index['prefixed_name'], 'class' => $entity],
$entityClassName::getEntities()
)
));
}

$output->writeln('<info>Done!</info>');

return 0;
return array_unique($indexes->all(), SORT_REGULAR);
}
}
100 changes: 44 additions & 56 deletions src/Command/MeilisearchImportCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,34 @@

use Doctrine\Persistence\ManagerRegistry;
use Meilisearch\Bundle\Collection;
use Meilisearch\Bundle\Exception\InvalidSettingName;
use Meilisearch\Bundle\EventListener\ConsoleOutputSubscriber;
use Meilisearch\Bundle\Exception\TaskException;
use Meilisearch\Bundle\Model\Aggregator;
use Meilisearch\Bundle\SearchService;
use Meilisearch\Bundle\SettingsProvider;
use Meilisearch\Bundle\Services\SettingsUpdater;
use Meilisearch\Client;
use Meilisearch\Exceptions\TimeOutException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

final class MeilisearchImportCommand extends IndexCommand
{
private const DEFAULT_RESPONSE_TIMEOUT = 5000;
private Client $searchClient;
private ManagerRegistry $managerRegistry;
private SettingsUpdater $settingsUpdater;
private EventDispatcherInterface $eventDispatcher;

protected Client $searchClient;
protected ManagerRegistry $managerRegistry;

public function __construct(SearchService $searchService, ManagerRegistry $managerRegistry, Client $searchClient)
public function __construct(SearchService $searchService, ManagerRegistry $managerRegistry, Client $searchClient, SettingsUpdater $settingsUpdater, EventDispatcherInterface $eventDispatcher)
{
parent::__construct($searchService);

$this->managerRegistry = $managerRegistry;
$this->searchClient = $searchClient;
$this->settingsUpdater = $settingsUpdater;
$this->eventDispatcher = $eventDispatcher;
}

public static function getDefaultName(): string
Expand All @@ -50,8 +54,9 @@ protected function configure(): void
->addOption(
'update-settings',
null,
InputOption::VALUE_NONE,
'Update settings related to indices to the search engine'
InputOption::VALUE_NEGATABLE,
'Update settings related to indices to the search engine',
true
)
->addOption('batch-size', null, InputOption::VALUE_REQUIRED)
->addOption(
Expand All @@ -73,32 +78,20 @@ protected function configure(): void

protected function execute(InputInterface $input, OutputInterface $output): int
{
$this->eventDispatcher->addSubscriber(new ConsoleOutputSubscriber(new SymfonyStyle($input, $output)));

$indexes = $this->getEntitiesFromArgs($input, $output);
$entitiesToIndex = $this->entitiesToIndex($indexes);
$config = $this->searchService->getConfiguration();

foreach ($indexes as $key => $index) {
$entityClassName = $index['class'];
if (is_subclass_of($entityClassName, Aggregator::class)) {
$indexes->forget($key);

$indexes = new Collection(array_merge(
$indexes->all(),
array_map(
fn ($entity) => ['class' => $entity],
$entityClassName::getEntities()
)
));
}
}

$entitiesToIndex = array_unique($indexes->all(), SORT_REGULAR);
$updateSettings = $input->getOption('update-settings');
$batchSize = $input->getOption('batch-size') ?? '';
$batchSize = ctype_digit($batchSize) ? (int) $batchSize : $config->get('batchSize');
$responseTimeout = ((int) $input->getOption('response-timeout')) ?: self::DEFAULT_RESPONSE_TIMEOUT;

/** @var array $index */
foreach ($entitiesToIndex as $index) {
$entityClassName = $index['class'];

if (!$this->searchService->isSearchable($entityClassName)) {
continue;
}
Expand Down Expand Up @@ -148,36 +141,8 @@ protected function execute(InputInterface $input, OutputInterface $output): int
);
}

if (isset($index['settings'])
&& is_array($index['settings'])
&& count($index['settings']) > 0) {
$indexInstance = $this->searchClient->index($index['name']);
foreach ($index['settings'] as $variable => $value) {
$method = sprintf('update%s', ucfirst($variable));

if (!method_exists($indexInstance, $method)) {
throw new InvalidSettingName(sprintf('Invalid setting name: "%s"', $variable));
}

if (isset($value['_service']) && $value['_service'] instanceof SettingsProvider) {
$value = $value['_service']();
} elseif ('distinctAttribute' === $variable && is_array($value)) {
$value = $value[0] ?? null;
}

// Update
$task = $indexInstance->{$method}($value);

// Get task information using uid
$indexInstance->waitForTask($task['taskUid'], $responseTimeout);
$task = $indexInstance->getTask($task['taskUid']);

if ('failed' === $task['status']) {
throw new TaskException($task['error']);
}

$output->writeln('<info>Settings updated of "'.$index['name'].'".</info>');
}
if ($updateSettings) {
$this->settingsUpdater->update($index['prefixed_name'], $responseTimeout);
}

++$page;
Expand Down Expand Up @@ -220,4 +185,27 @@ private function formatIndexingResponse(array $batch, int $responseTimeout): arr

return $formattedResponse;
}

private function entitiesToIndex($indexes): array
{
foreach ($indexes as $key => $index) {
$entityClassName = $index['class'];

if (!is_subclass_of($entityClassName, Aggregator::class)) {
continue;
}

$indexes->forget($key);

$indexes = new Collection(array_merge(
$indexes->all(),
array_map(
static fn ($entity) => ['name' => $index['name'], 'prefixed_name' => $index['prefixed_name'], 'class' => $entity],
$entityClassName::getEntities()
)
));
}

return array_unique($indexes->all(), SORT_REGULAR);
}
}
1 change: 1 addition & 0 deletions src/DependencyInjection/MeilisearchExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ public function load(array $configs, ContainerBuilder $container): void
}

foreach ($config['indices'] as $index => $indice) {
$config['indices'][$index]['prefixed_name'] = $config['prefix'].$indice['name'];
$config['indices'][$index]['settings'] = $this->findReferences($config['indices'][$index]['settings']);
}

Expand Down
Loading