TermsAggregation example

/** * @internal * * @covers \Shopware\Elasticsearch\Framework\DataAbstractionLayer\CriteriaParser */
class CriteriaParserTest extends TestCase
{
    private const SECOND_LANGUAGE = 'd5da80fc94874ea988eac8abdea44e0a';

    public function testAggregationWithSorting(): void
    {
        $aggs = new TermsAggregation('foo', 'test', null, new FieldSorting('abc', FieldSorting::ASCENDING)new TermsAggregation('foo', 'foo2'));

        $definition = $this->getDefinition();

        /** @var CompositeAggregation $esAgg */
        $esAgg = (new CriteriaParser(
            new EntityDefinitionQueryHelper(),
            $this->createMock(CustomFieldService::class),
            $this->createMock(AbstractKeyValueStorage::class)
        ))->parseAggregation($aggs$definition, Context::createDefaultContext());

        static::assertInstanceOf(CompositeAggregation::class$esAgg);
        
return ExtensionStruct::fromArray($this->replaceCollections($data));
    }

    /** * @return array<string> */
    private function getInstalledThemeNames(Context $context): array
    {
        if ($this->installedThemeNames === null && $this->themeRepository instanceof EntityRepository) {
            $themeNameAggregationName = 'theme_names';
            $criteria = new Criteria();
            $criteria->addAggregation(new TermsAggregation($themeNameAggregationName, 'technicalName'));

            /** @var TermsResult $themeNameAggregation */
            $themeNameAggregation = $this->themeRepository->aggregate($criteria$context)->get($themeNameAggregationName);

            return $this->installedThemeNames = $themeNameAggregation->getKeys();
        }

        return $this->installedThemeNames ?? [];
    }

    private function loadLocalAppsCollection(Context $context): ExtensionCollection
    {
/** * @depends testIndexing */
    public function testTermsAggregation(IdsCollection $data): void
    {
        try {
            $aggregator = $this->createEntityAggregator();

            // check simple search without any restrictions             $criteria = new Criteria($data->prefixed('product-'));
            $criteria->addState(Criteria::STATE_ELASTICSEARCH_AWARE);
            $criteria->addAggregation(new TermsAggregation('manufacturer-ids', 'product.manufacturerId'));

            $aggregations = $aggregator->aggregate($this->productDefinition, $criteria$this->context);

            static::assertCount(1, $aggregations);

            static::assertTrue($aggregations->has('manufacturer-ids'));

            $result = $aggregations->get('manufacturer-ids');
            static::assertInstanceOf(TermsResult::class$result);

            static::assertCount(3, $result->getBuckets());

            
$naturalSorting = $sort['naturalSorting'] ?? false;

                    if (strcasecmp((string) $order, 'desc') === 0) {
                        $order = FieldSorting::DESCENDING;
                    } else {
                        $order = FieldSorting::ASCENDING;
                    }

                    $sorting = new FieldSorting($sort['field']$order(bool) $naturalSorting);
                }

                return new TermsAggregation($name$field$limit$sorting$nested);

            default:
                $exceptions->add(new InvalidAggregationQueryException(sprintf('The aggregation type "%s" used as key does not exists.', $type)), '/aggregations/' . $index);

                return null;
        }
    }

    private static function buildFieldName(EntityDefinition $definition, string $fieldName): string
    {
        $prefix = $definition->getEntityName() . '.';

        
$criteria->addPostFilter(new MultiFilter(MultiFilter::CONNECTION_OR, $pointFilter));
        }

        $reviewFilters[] = new EqualsFilter('status', true);
        if ($context->getCustomer() !== null) {
            $reviewFilters[] = new EqualsFilter('customerId', $context->getCustomer()->getId());
        }

        $criteria->addAggregation(
            new FilterAggregation(
                'customer-login-filter',
                new TermsAggregation('ratingMatrix', 'points'),
                [
                    new MultiFilter(MultiFilter::CONNECTION_OR, $reviewFilters),
                ]
            )
        );
    }
}
$aggregations->add(new EntityResult('properties', $grouped));
    }

    /** * @param array<string>|null $groupIds */
    private function getPropertyFilter(Request $request, ?array $groupIds = null): Filter
    {
        $ids = $this->getPropertyIds($request);

        $propertyAggregation = new TermsAggregation('properties', 'product.properties.id');

        $optionAggregation = new TermsAggregation('options', 'product.options.id');

        if ($groupIds) {
            $propertyAggregation = new FilterAggregation(
                'properties-filter',
                $propertyAggregation,
                [new EqualsAnyFilter('product.properties.groupId', $groupIds)]
            );

            $optionAggregation = new FilterAggregation(
                


    public function testSingleTermsAggregation(): void
    {
        $context = Context::createDefaultContext();

        $criteria = new Criteria(
            $this->ids->getList(['p-1', 'p-2', 'p-3', 'p-4', 'p-5'])
        );

        $criteria->addAggregation(
            new TermsAggregation('category-ids', 'product.categories.id')
        );

        $result = $this->aggregator->aggregate($this->definition, $criteria$context);

        static::assertTrue($result->has('category-ids'));

        $categoryAgg = $result->get('category-ids');
        static::assertInstanceOf(TermsResult::class$categoryAgg);

        static::assertCount(4, $categoryAgg->getBuckets());
        static::assertTrue($categoryAgg->has(''));
        
$themeId = $this->getThemeIdByTechnicalName($technicalName$context);

        if ($themeId === null) {
            // extension is not a theme             return;
        }

        $criteria = new Criteria();
        $criteria->addAggregation(
            new FilterAggregation(
                'assigned_theme_filter',
                new TermsAggregation('assigned_theme', 'themes.id'),
                [new EqualsFilter('themes.id', $themeId)]
            )
        );
        $criteria->addAggregation(
            new FilterAggregation(
                'assigned_children_filter',
                new TermsAggregation('assigned_children', 'themes.parentThemeId'),
                [new EqualsFilter('themes.parentThemeId', $themeId)]
            )
        );

        
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;

/** * @internal * * @covers \Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Bucket\FilterAggregation */
class FilterAggregationTest extends TestCase
{
    public function testEncode(): void
    {
        $aggregation = new FilterAggregation('foo', new TermsAggregation('foo', 'name')[new EqualsFilter('name', 'test')]);
        static::assertEquals([
            'name' => 'foo',
            'extensions' => [],
            'field' => '',
            'aggregation' => [
                'extensions' => [],
                'name' => 'foo',
                'field' => 'name',
                'aggregation' => null,
                'limit' => null,
                'sorting' => null,
                
// Fetch additional level of categories for counting visible children that are NOT included in the original query         $criteria = new Criteria();
        $criteria->addFilter(
            new ContainsFilter('path', '|' . $rootId . '|'),
            new EqualsFilter('level', $rootLevel + $depth + 1),
            new EqualsFilter('active', true),
            new EqualsFilter('visible', true)
        );

        $criteria->addAggregation(
            new TermsAggregation('category-ids', 'parentId', null, null, new CountAggregation('visible-children-count', 'id'))
        );

        $termsResult = $this->categoryRepository
            ->aggregate($criteria$context)
            ->get('category-ids');

        if (!($termsResult instanceof TermsResult)) {
            return;
        }

        foreach ($termsResult->getBuckets() as $bucket) {
            
return $result;
    }

    /** * @return array<int, int|string> */
    public function getAuthors(Context $context): array
    {
        $files = $this->snippetFileCollection->toArray();

        $criteria = new Criteria();
        $criteria->addAggregation(new TermsAggregation('distinct_author', 'author'));

        /** @var TermsResult|null $aggregation */
        $aggregation = $this->snippetRepository->aggregate($criteria$context)
                ->get('distinct_author');

        if (!$aggregation || empty($aggregation->getBuckets())) {
            $result = [];
        } else {
            $result = $aggregation->getKeys();
        }

        
use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Bucket\TermsAggregation;

/** * @internal * * @covers \Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Bucket\TermsAggregation */
class TermsAggregationTest extends TestCase
{
    public function testEncode(): void
    {
        $aggregation = new TermsAggregation('foo', 'name');
        static::assertEquals([
            'name' => 'foo',
            'extensions' => [],
            'field' => 'name',
            'aggregation' => null,
            'limit' => null,
            'sorting' => null,
            '_class' => TermsAggregation::class,
        ]$aggregation->jsonSerialize());
    }

    
'gte' => $point - 0.5,
                    'lt' => $point + 0.5,
                ]);
            }

            $criteria->addPostFilter(new MultiFilter(MultiFilter::CONNECTION_OR, $pointFilter));
        }

        $criteria->addAggregation(
            new FilterAggregation(
                'status-filter',
                new TermsAggregation('ratingMatrix', 'points'),
                [new EqualsFilter('status', 1)]
            )
        );
    }

    private function getCustomerReview(string $productId, SalesChannelContext $context): ?ProductReviewEntity
    {
        $customer = $context->getCustomer();

        if (!$customer) {
            return null;
        }
yield 'filter+sort' => [
            (new Criteria())->addFilter(new PrefixFilter('foo', 'bar'))->addSorting(new FieldSorting('foo')),
            'c5d7faee1a855cfdf7f4a5a8807ec0f0',
        ];

        yield 'filter+sort+sort-desc' => [
            (new Criteria())->addFilter(new PrefixFilter('foo', 'bar'))->addSorting(new FieldSorting('foo', FieldSorting::DESCENDING)),
            'fd5017a9b079d29a790ea9682c11ed74',
        ];

        yield 'filter+agg' => [
            (new Criteria())->addFilter(new PrefixFilter('foo', 'bar'))->addAggregation(new TermsAggregation('foo', 'foo')),
            'c8dcaf7970a7ec0a42e52047f0b60b1a',
        ];
    }

    /** * @dataProvider contextHashProvider */
    public function testContextHash(SalesChannelContext $compared): void
    {
        $generator = new EntityCacheKeyGenerator();

        
$store,
            ApiProtectionException::class,
        ];

        yield 'Test query order line item access in store api' => [
            (new Criteria())->addQuery(new ScoreQuery(new EqualsFilter('orderLineItems.id', 1), 100)),
            $store,
            ApiProtectionException::class,
        ];

        yield 'Test aggregation order line item access in store api' => [
            (new Criteria())->addAggregation(new TermsAggregation('agg', 'orderLineItems.id')),
            $store,
            ApiProtectionException::class,
        ];

        yield 'Test filter for runtime field' => [
            (new Criteria())->addFilter(new ContainsFilter('variation', Uuid::randomHex())),
            $admin,
            RuntimeFieldInCriteriaException::class,
        ];

        yield 'Test aggregate for runtime field' => [
            (
Home | Imprint | This part of the site doesn't use cookies.