Skip to content

Allowing different entities indexed into same index #92

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 4 commits into from
Jun 22, 2021
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
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,3 @@
.phpunit.result.cache
/var/
.php-cs-fixer.cache
/tests/cache/blog.sqlite
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"php": "^7.4|^8.0",
"ext-json": "*",
"doctrine/doctrine-bundle": "^2.4",
"illuminate/collections": "^8.47",
"meilisearch/meilisearch-php": "^0.18",
"symfony/filesystem": "^4.0 || ^5.0",
"symfony/property-access": "^4.0 || ^5.0",
Expand Down
50 changes: 25 additions & 25 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true" bootstrap="vendor/autoload.php" convertDeprecationsToExceptions="false">
<php>
<env name="KERNEL_CLASS" value="MeiliSearch\Bundle\Test\Kernel"/>
<env name="APP_ENV" value="test"/>
<env name="APP_DEBUG" value="false"/>
<env name="MEILISEARCH_PREFIX" value="sf_phpunit_"/>
<env name="MEILISEARCH_URL" value="http://127.0.0.1:7700"/>
<env name="MEILISEARCH_API_KEY" value="masterKey"/>
<env name="TRAVIS_JOB_NUMBER" value=""/>
<env name="SYMFONY_DEPRECATIONS_HELPER" value="disabled"/>
</php>
<testsuites>
<testsuite name="TestCase">
<directory suffix=".php">tests/TestCase/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>src/</directory>
<exclude>
<file>src/DependencyInjection/MeiliSearchExtension.php</file>
<file>src/Services/NullSearchService.php</file>
</exclude>
</whitelist>
</filter>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" colors="true" bootstrap="vendor/autoload.php" convertDeprecationsToExceptions="false" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage>
<include>
<directory>src/</directory>
</include>
<exclude>
<file>src/DependencyInjection/MeiliSearchExtension.php</file>
<file>src/Services/NullSearchService.php</file>
</exclude>
</coverage>
<php>
<env name="KERNEL_CLASS" value="MeiliSearch\Bundle\Test\Kernel"/>
<env name="APP_ENV" value="test"/>
<env name="APP_DEBUG" value="false"/>
<env name="MEILISEARCH_PREFIX" value="sf_phpunit_"/>
<env name="MEILISEARCH_URL" value="http://127.0.0.1:7700"/>
<env name="MEILISEARCH_API_KEY" value="masterKey"/>
<env name="TRAVIS_JOB_NUMBER" value=""/>
<env name="SYMFONY_DEPRECATIONS_HELPER" value="disabled"/>
</php>
<testsuites>
<testsuite name="TestCase">
<directory suffix=".php">tests/TestCase/</directory>
</testsuite>
</testsuites>
</phpunit>
51 changes: 30 additions & 21 deletions src/Command/IndexCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace MeiliSearch\Bundle\Command;

use Illuminate\Support\Collection;
use MeiliSearch\Bundle\SearchService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
Expand All @@ -14,28 +15,47 @@
*/
abstract class IndexCommand extends Command
{
private string $prefix;
protected SearchService $searchService;

public function __construct(SearchService $searchService, ?string $name = null)
{
$this->searchService = $searchService;
$this->prefix = $this->searchService->getConfiguration()->get('prefix');

parent::__construct($name);
}

protected function getEntitiesFromArgs(InputInterface $input, OutputInterface $output): array
protected function getIndices(): Collection
{
return collect($this->searchService->getConfiguration()->get('indices'))
->transform(function (array $item) {
$item['name'] = $this->prefix.$item['name'];

return $item;
});
}

protected function getEntitiesFromArgs(InputInterface $input, OutputInterface $output): Collection
{
$entities = [];
$indexNames = [];
$indexNames = collect();

if ($indexList = $input->getOption('indices')) {
$indexNames = \explode(',', $indexList);
$list = \explode(',', $indexList);
$indexNames = collect($list)->transform(function (string $item) {
// Check if the given index name already contains the prefix
if (false === strpos($item, $this->prefix)) {
return $this->prefix.$item;
}

return $item;
});
}

$config = $this->searchService->getConfiguration();

if ((0 === count($indexNames))
&& !empty(array_keys($config['indices']))) {
$indexNames = array_keys($config['indices']);
if ((0 === count($indexNames)) && count($config->get('indices')) > 0) {
$indexNames = $this->getIndices();
}

if (0 === count($indexNames)) {
Expand All @@ -44,19 +64,8 @@ protected function getEntitiesFromArgs(InputInterface $input, OutputInterface $o
);
}

foreach ($indexNames as $name) {
if (isset($config['indices'][$name])) {
$entities[$name]['name'] = $config['indices'][$name]['class'];
if (true === $input->hasOption('update-settings') && !empty($config['indices'][$name]['settings'])) {
$entities[$name]['settings'] = $config['indices'][$name]['settings'];
}
} else {
$output->writeln(
'<comment>No index named <info>'.$name.'</info> was found. Check you configuration.</comment>'
);
}
}

return $entities;
return collect($this->getIndices())->reject(function (array $item) use ($indexNames) {
return !in_array($item['name'], $indexNames->toArray(), true);
});
}
}
14 changes: 9 additions & 5 deletions src/Command/MeiliSearchClearCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,22 @@ protected function execute(InputInterface $input, OutputInterface $output): int
{
$indexToClear = $this->getEntitiesFromArgs($input, $output);

foreach ($indexToClear as $indexName => $entity) {
$className = $entity['name'];
/** @var array $index */
foreach ($indexToClear as $index) {
$indexName = $index['name'];
$className = $index['class'];
$array = $this->searchService->clear($className);
if ('failed' === $array['status']) {
$output->writeln('<error>Index <info>'.$indexName.'</info> couldn\'t be cleared</error>');
} else {
$output->writeln(
'Cleared <info>'.$indexName.'</info> index of <comment>'.$className.'</comment> '
);
$output->writeln('Cleared <info>'.$indexName.'</info> index of <comment>'.$className.'</comment>');
}
}

if (0 === count($indexToClear)) {
$output->writeln('Cannot clear index. Not found.');
}

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

return 0;
Expand Down
40 changes: 23 additions & 17 deletions src/Command/MeiliSearchImportCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,43 +45,47 @@ protected function configure()

protected function execute(InputInterface $input, OutputInterface $output): int
{
$entitiesToIndex = $this->getEntitiesFromArgs($input, $output);
$indexes = $this->getEntitiesFromArgs($input, $output);
$config = $this->searchService->getConfiguration();

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

$indexes = collect(array_merge(
$indexes->toArray(),
array_map(
function ($entity) {
return ['name' => $entity];
return ['class' => $entity];
},
$entityClassName::getEntities()
)
);
));
}
}

$entitiesToIndex = array_unique($entitiesToIndex, SORT_REGULAR);
$entitiesToIndex = array_unique($indexes->toArray(), SORT_REGULAR);

foreach ($entitiesToIndex as $index => $entity) {
$entityClassName = $entity['name'];
/** @var array $index */
foreach ($entitiesToIndex as $index) {
$entityClassName = $index['class'];
if (!$this->searchService->isSearchable($entityClassName)) {
continue;
}

$manager = $this->managerRegistry->getManagerForClass($entityClassName);
$repository = $manager->getRepository($entityClassName);

$output->writeln('<info>Importing for index '.$entityClassName.'</info>');

$page = 0;
do {
$entities = $repository->findBy(
[],
null,
$config['batchSize'],
$config['batchSize'] * $page
$config->get('batchSize'),
$config->get('batchSize') * $page
);

$responses = $this->formatIndexingResponse($this->searchService->index($manager, $entities));
Expand All @@ -97,9 +101,9 @@ function ($entity) {
);
}

if (!empty($entity['settings'])) {
$indexInstance = $this->searchClient->getOrCreateIndex($config['prefix'].$index);
foreach ($entity['settings'] as $variable => $value) {
if (!empty($index['settings'])) {
$indexInstance = $this->searchClient->getOrCreateIndex($index['name']);
foreach ($index['settings'] as $variable => $value) {
$method = sprintf('update%s', ucfirst($variable));
if (false === method_exists($indexInstance, $method)) {
throw new InvalidSettingName(sprintf('Invalid setting name: "%s"', $variable));
Expand All @@ -114,12 +118,14 @@ function ($entity) {

if ('failed' === $updateStatus['status']) {
throw new UpdateException($updateStatus['error']);
} else {
$output->writeln('<info>Settings updated.</info>');
}
}
}

++$page;
} while (count($entities) >= $config['batchSize']);
} while (count($entities) >= $config->get('batchSize'));

$manager->clear();
}
Expand Down
5 changes: 4 additions & 1 deletion src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,12 @@ public function getConfigTreeBuilder(): TreeBuilder
->defaultValue('serializer')
->end()
->arrayNode('indices')
->useAttributeAsKey('name')
->arrayPrototype()
->children()
->scalarNode('name')
->isRequired()
->cannotBeEmpty()
->end()
->scalarNode('class')
->isRequired()
->cannotBeEmpty()
Expand Down
6 changes: 5 additions & 1 deletion src/Engine.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public function __construct(Client $client)
public function index($searchableEntities): array
{
if ($searchableEntities instanceof SearchableEntity) {
/** @var SearchableEntity[] $searchableEntities */
$searchableEntities = [$searchableEntities];
}

Expand Down Expand Up @@ -70,10 +71,13 @@ public function index($searchableEntities): array
public function remove($searchableEntities): array
{
if ($searchableEntities instanceof SearchableEntity) {
/** @var SearchableEntity[] $searchableEntities */
$searchableEntities = [$searchableEntities];
}

$data = [];

/** @var SearchableEntity $entity */
foreach ($searchableEntities as $entity) {
$searchableArray = $entity->getSearchableArray();
if (null === $searchableArray || 0 === \count($searchableArray)) {
Expand Down Expand Up @@ -137,6 +141,6 @@ public function search(string $query, string $indexUid, array $searchParams): ar
*/
public function count(string $query, string $indexName, array $searchParams): int
{
return (int) $this->client->index($indexName)->search($query, $searchParams)['nbHits'];
return $this->client->index($indexName)->search($query, $searchParams)->getHitsCount();
}
}
3 changes: 0 additions & 3 deletions src/Exception/InvalidEntityForAggregator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@

namespace MeiliSearch\Bundle\Exception;

/**
* Class InvalidEntityForAggregator.
*/
final class InvalidEntityForAggregator extends \LogicException
{
}
5 changes: 4 additions & 1 deletion src/SearchService.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace MeiliSearch\Bundle;

use Doctrine\Persistence\ObjectManager;
use Illuminate\Support\Collection;

/**
* Interface SearchService.
Expand All @@ -21,7 +22,7 @@ public function isSearchable($className): bool;

public function getSearchable(): array;

public function getConfiguration(): array;
public function getConfiguration(): Collection;

/**
* Get the index name for the given `$className`.
Expand All @@ -36,6 +37,8 @@ public function clear(string $className): array;

public function delete(string $className): ?array;

public function deleteByIndexName(string $indexName): ?array;

public function search(
ObjectManager $objectManager,
string $className,
Expand Down
2 changes: 1 addition & 1 deletion src/SearchableEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public function __construct(
$this->setId();
}

public function getindexUid(): string
public function getIndexUid(): string
{
return $this->indexUid;
}
Expand Down
Loading