vendor/shopware/elasticsearch/Framework/DataAbstractionLayer/ElasticsearchEntitySearcher.php line 62

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Elasticsearch\Framework\DataAbstractionLayer;
  3. use Elasticsearch\Client;
  4. use ONGR\ElasticsearchDSL\Aggregation\AbstractAggregation;
  5. use ONGR\ElasticsearchDSL\Aggregation\Bucketing\FilterAggregation;
  6. use ONGR\ElasticsearchDSL\Aggregation\Metric\CardinalityAggregation;
  7. use ONGR\ElasticsearchDSL\Search;
  8. use Shopware\Core\Framework\Context;
  9. use Shopware\Core\Framework\DataAbstractionLayer\EntityDefinition;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Search\EntitySearcherInterface;
  12. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Search\Grouping\FieldGrouping;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Search\IdSearchResult;
  15. use Shopware\Core\Framework\Log\Package;
  16. use Shopware\Elasticsearch\Framework\DataAbstractionLayer\Event\ElasticsearchEntitySearcherSearchEvent;
  17. use Shopware\Elasticsearch\Framework\ElasticsearchHelper;
  18. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  19. #[Package('core')]
  20. class ElasticsearchEntitySearcher implements EntitySearcherInterface
  21. {
  22.     public const MAX_LIMIT 10000;
  23.     public const RESULT_STATE 'loaded-by-elastic';
  24.     private Client $client;
  25.     private EntitySearcherInterface $decorated;
  26.     private ElasticsearchHelper $helper;
  27.     private CriteriaParser $criteriaParser;
  28.     private AbstractElasticsearchSearchHydrator $hydrator;
  29.     private EventDispatcherInterface $eventDispatcher;
  30.     /**
  31.      * @internal
  32.      */
  33.     public function __construct(
  34.         Client $client,
  35.         EntitySearcherInterface $searcher,
  36.         ElasticsearchHelper $helper,
  37.         CriteriaParser $criteriaParser,
  38.         AbstractElasticsearchSearchHydrator $hydrator,
  39.         EventDispatcherInterface $eventDispatcher
  40.     ) {
  41.         $this->client $client;
  42.         $this->decorated $searcher;
  43.         $this->helper $helper;
  44.         $this->criteriaParser $criteriaParser;
  45.         $this->hydrator $hydrator;
  46.         $this->eventDispatcher $eventDispatcher;
  47.     }
  48.     public function search(EntityDefinition $definitionCriteria $criteriaContext $context): IdSearchResult
  49.     {
  50.         if (!$this->helper->allowSearch($definition$context$criteria)) {
  51.             return $this->decorated->search($definition$criteria$context);
  52.         }
  53.         if ($criteria->getLimit() === 0) {
  54.             return new IdSearchResult(0, [], $criteria$context);
  55.         }
  56.         $search $this->createSearch($criteria$definition$context);
  57.         $this->eventDispatcher->dispatch(
  58.             new ElasticsearchEntitySearcherSearchEvent(
  59.                 $search,
  60.                 $definition,
  61.                 $criteria,
  62.                 $context
  63.             )
  64.         );
  65.         $search $this->convertSearch($criteria$definition$context$search);
  66.         try {
  67.             $result $this->client->search([
  68.                 'index' => $this->helper->getIndexName($definition$context->getLanguageId()),
  69.                 'track_total_hits' => true,
  70.                 'body' => $search,
  71.             ]);
  72.         } catch (\Throwable $e) {
  73.             $this->helper->logAndThrowException($e);
  74.             return $this->decorated->search($definition$criteria$context);
  75.         }
  76.         $result $this->hydrator->hydrate($definition$criteria$context$result);
  77.         $result->addState(self::RESULT_STATE);
  78.         return $result;
  79.     }
  80.     private function createSearch(Criteria $criteriaEntityDefinition $definitionContext $context): Search
  81.     {
  82.         $search = new Search();
  83.         $this->helper->handleIds($definition$criteria$search$context);
  84.         $this->helper->addFilters($definition$criteria$search$context);
  85.         $this->helper->addPostFilters($definition$criteria$search$context);
  86.         $this->helper->addQueries($definition$criteria$search$context);
  87.         $this->helper->addSortings($definition$criteria$search$context);
  88.         $this->helper->addTerm($criteria$search$context$definition);
  89.         $search->setSize(self::MAX_LIMIT);
  90.         $limit $criteria->getLimit();
  91.         if ($limit !== null) {
  92.             $search->setSize($limit);
  93.         }
  94.         $search->setFrom((int) $criteria->getOffset());
  95.         return $search;
  96.     }
  97.     /**
  98.      * @return array<string, mixed>
  99.      */
  100.     private function convertSearch(Criteria $criteriaEntityDefinition $definitionContext $contextSearch $search): array
  101.     {
  102.         if (!$criteria->getGroupFields()) {
  103.             return $search->toArray();
  104.         }
  105.         $aggregation $this->buildTotalCountAggregation($criteria$definition$context);
  106.         $search->addAggregation($aggregation);
  107.         $array $search->toArray();
  108.         $array['collapse'] = $this->parseGrouping($criteria->getGroupFields(), $definition$context);
  109.         return $array;
  110.     }
  111.     /**
  112.      * @param FieldGrouping[] $groupings
  113.      *
  114.      * @return array{field: string, inner_hits?: array{name: string}}
  115.      */
  116.     private function parseGrouping(array $groupingsEntityDefinition $definitionContext $context): array
  117.     {
  118.         /** @var FieldGrouping $grouping */
  119.         $grouping array_shift($groupings);
  120.         $accessor $this->criteriaParser->buildAccessor($definition$grouping->getField(), $context);
  121.         if (empty($groupings)) {
  122.             return ['field' => $accessor];
  123.         }
  124.         return [
  125.             'field' => $accessor,
  126.             'inner_hits' => [
  127.                 'name' => 'inner',
  128.                 'collapse' => $this->parseGrouping($groupings$definition$context),
  129.             ],
  130.         ];
  131.     }
  132.     private function buildTotalCountAggregation(Criteria $criteriaEntityDefinition $definitionContext $context): AbstractAggregation
  133.     {
  134.         $groupings $criteria->getGroupFields();
  135.         if (\count($groupings) === 1) {
  136.             $first array_shift($groupings);
  137.             $accessor $this->criteriaParser->buildAccessor($definition$first->getField(), $context);
  138.             $aggregation = new CardinalityAggregation('total-count');
  139.             $aggregation->setField($accessor);
  140.             return $this->addPostFilterAggregation($criteria$definition$context$aggregation);
  141.         }
  142.         $fields = [];
  143.         foreach ($groupings as $grouping) {
  144.             $accessor $this->criteriaParser->buildAccessor($definition$grouping->getField(), $context);
  145.             $fields[] = sprintf(
  146.                 '
  147.                 if (doc[\'%s\'].size()==0) {
  148.                     value = value + \'empty\';
  149.                 } else {
  150.                     value = value + doc[\'%s\'].value;
  151.                 }',
  152.                 $accessor,
  153.                 $accessor
  154.             );
  155.         }
  156.         $script '
  157.             def value = \'\';
  158.             ' implode(' '$fields) . '
  159.             return value;
  160.         ';
  161.         $aggregation = new CardinalityAggregation('total-count');
  162.         $aggregation->setScript($script);
  163.         return $this->addPostFilterAggregation($criteria$definition$context$aggregation);
  164.     }
  165.     private function addPostFilterAggregation(Criteria $criteriaEntityDefinition $definitionContext $contextCardinalityAggregation $aggregation): AbstractAggregation
  166.     {
  167.         if (!$criteria->getPostFilters()) {
  168.             return $aggregation;
  169.         }
  170.         $query $this->criteriaParser->parseFilter(
  171.             new MultiFilter(MultiFilter::CONNECTION_AND$criteria->getPostFilters()),
  172.             $definition,
  173.             $definition->getEntityName(),
  174.             $context
  175.         );
  176.         $filterAgg = new FilterAggregation('total-filtered-count'$query);
  177.         $filterAgg->addAggregation($aggregation);
  178.         return $filterAgg;
  179.     }
  180. }