### Create Replicas Usage Example Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ReplicaManager.md Example of configuring and creating replica indices. ```php $sortConfigs = [ ['attribute' => 'price', 'direction' => 'asc'], // Price: Low to High ['attribute' => 'price', 'direction' => 'desc'], // Price: High to Low ['attribute' => 'name', 'direction' => 'asc'], // Name: A to Z ['attribute' => 'popularity', 'direction' => 'desc'], // Most Popular ]; $replicaManager->createReplicas($indexOptions, $sortConfigs, true); ``` -------------------------------- ### Install customization starter module Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/README.md Use this command to install the boilerplate module for extending the base integration. ```bash composer require algolia/algoliasearch-custom-algolia-magento-2 ``` -------------------------------- ### buildIndexFull Usage Example Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/IndexBuilder.md Example demonstrating how to trigger a full reindex for all products. ```php // Full reindex all products $indexBuilder->buildIndexFull($storeId); ``` -------------------------------- ### buildIndex Usage Examples Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/IndexBuilder.md Examples demonstrating how to index specific products, perform incremental indexing, or use temporary indices. ```php // Index specific products $indexBuilder->buildIndex($storeId, [123, 456], null); // Full incremental index (all recent changes) $indexBuilder->buildIndex($storeId, null, null); // Index to temporary index $indexBuilder->buildIndex($storeId, null, ['tmp' => true]); ``` -------------------------------- ### getClient Usage Example Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/SearchClientProvider.md Examples of retrieving a client for the current or a specific store and performing a search. ```php // Get client for current store $client = $provider->getClient(); // Get client for specific store $client = $provider->getClient(2); // Use the client $results = $client->search($indexName, $searchQuery); ``` -------------------------------- ### LandingPage Usage Example Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/types.md Retrieving a landing page via repository and accessing its properties. ```php $landingPage = $landingPageRepository->getById($id); echo $landingPage->getName(); // 'Summer Sale' echo $landingPage->getUrl(); // 'summer-sale' echo $landingPage->getStatus(); // 1 (enabled) ``` -------------------------------- ### Install MSI compatibility module Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/README.md Use this command to install the module enabling Algolia indexing compatibility with Magento's Multi-Source Inventory (MSI) system. ```bash composer require algolia/algoliasearch-inventory-magento-2 ``` -------------------------------- ### Query Usage Example Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/types.md Retrieving a search query via repository and accessing its properties. ```php $query = $queryRepository->getById($id); echo $query->getQuery(); // 'summer dresses' echo $query->getRedirectUrl(); // 'https://example.com/summer-collection' ``` -------------------------------- ### Install ingestion module Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/README.md Use this command to route product indexing through the Algolia Ingestion API. ```bash composer require algolia/algoliasearch-ingestion-magento-2 ``` -------------------------------- ### Execute processBatch Examples Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/BatchQueueProcessor.md Demonstrates processing specific entity IDs versus processing all queued jobs for a store. ```php // Process specific product IDs $batchProcessor->processBatch($storeId, [123, 456, 789]); // Process queued jobs for the store $batchProcessor->processBatch($storeId, null); ``` -------------------------------- ### Delete Replicas Usage Example Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ReplicaManager.md Example of deleting all replica indices for a main index. ```php $replicaManager->deleteReplicas($indexOptions); // Deletes: magento_products_store1_replica_asc_price, magento_products_store1_replica_desc_price, etc. ``` -------------------------------- ### Build a product record Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/RecordBuilder.md Example usage of the product record builder to retrieve and display record fields. ```php $product = $productRepository->getById(123); $record = $productRecordBuilder->buildRecord($product); echo $record['objectID']; // 'magento_product_123_1' echo $record['name']; // 'Product Name' ``` -------------------------------- ### Access IndexOptions Data Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/types.md Example usage of the IndexOptions object to retrieve configuration values. ```php $indexOptions = $optionsBuilder->build($storeId); echo $indexOptions->getIndexName(); // 'magento_products_store1' echo $indexOptions->getStoreId(); // 1 echo $indexOptions->isTemporaryIndex(); // false ``` -------------------------------- ### Install search adapter module Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/README.md Use this command to register Algolia as a native Magento search engine backend for server-side rendering. ```bash composer require algolia/algoliasearch-adapter-magento-2 ``` -------------------------------- ### View Project File Structure Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/INDEX.md Displays the directory layout of the documentation files to help locate specific API references and configuration guides. ```text output/ ├── README.md # Start here - architecture overview ├── configuration.md # Complete configuration reference ├── types.md # Data type definitions ├── errors.md # Exception reference ├── INDEX.md # This file └── api-reference/ ├── AlgoliaConnector.md # Main API bridge ├── SearchClientProvider.md # Client factory ├── IndexBuilder.md # Index building ├── RecordBuilder.md # Record building ├── BatchQueueProcessor.md # Queue processing ├── ConfigHelper.md # Configuration access ├── ReplicaManager.md # Replica management └── EventProcessor.md # Analytics tracking ``` -------------------------------- ### Product Record Structure Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/README.md Example of the data structure for a product record indexed in Algolia. ```php [ 'objectID' => 'magento_product_123_1', 'name' => 'Blue T-Shirt', 'sku' => 'TS-BLUE-M', 'type_id' => 'configurable', 'categories' => ['Clothing', 'Clothing > T-Shirts'], 'description' => '...', 'price' => 29.99, 'in_stock' => true, 'image_url' => 'https://example.com/product/image.jpg', 'url' => 'https://example.com/product.html', 'popularity' => 125, '_store_id' => 1, // Additional custom attributes... ] ``` -------------------------------- ### Define Custom Ranking Attributes Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ReplicaManager.md Configuration example showing how custom ranking attributes map to generated replica names. ```php // Configuration defines custom ranking attributes 'custom_ranking' => ['desc(popularity)', 'asc(price)'] // Creates replicas: // - magento_products_store1_replica_desc_popularity // - magento_products_store1_replica_asc_price // - magento_products_store1_replica_desc_popularity_asc_price ``` -------------------------------- ### Batch Operation Methods and Usage Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/SearchClientProvider.md Methods for executing multiple operations in a single request, including an example of the request structure. ```php public function batch(string $indexName, array $requests): array public function batch(array $requests): array ``` ```php $requests = [ ['action' => 'addObject', 'body' => $object1], ['action' => 'updateObject', 'body' => $object2], ['action' => 'deleteObject', 'objectID' => $objectId3], ]; $client->batch($indexName, $requests); ``` -------------------------------- ### Initialize and Search with AlgoliaConnector Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/AlgoliaConnector.md Demonstrates how to inject the connector and perform a search query using a built index configuration. ```php optionsBuilder->build($storeId); $searchQuery = $this->queryFactory->create([ 'indexName' => $options->getIndexName(), 'query' => $query, 'hitsPerPage' => 20, ]); return $this->connector->query($searchQuery); } } ``` -------------------------------- ### Create and execute a search query Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/types.md Demonstrates creating a search query using a factory and executing it via a connector. ```php // Create a search query $query = $this->searchQueryFactory->create([ 'indexOptions' => $indexOptions, 'query' => 'blue shirt', 'params' => [ 'hitsPerPage' => 20, 'page' => 0, 'facets' => ['category', 'color'], ] ]); $results = $connector->query($query); ``` -------------------------------- ### Get connection timeout Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the connection timeout setting in seconds. ```php public function getConnectionTimeout(?int $storeId = null): int ``` -------------------------------- ### Product Configuration Methods Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Methods to retrieve product-specific indexing and display settings. ```php public function getProductAttributes(?int $storeId = null): array ``` ```php public function getProductCustomRanking(?int $storeId = null): array ``` ```php public function includeNonVisibleProducts(?int $storeId = null): bool ``` ```php public function shouldEnableVisualMerchandising(?int $storeId = null): bool ``` ```php public function getImageWidth(?int $storeId = null): int ``` ```php public function getImageHeight(?int $storeId = null): int ``` -------------------------------- ### Get non-castable attributes Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the list of attributes that should not be type-cast in records. ```php public function getNonCastableAttributes(?int $storeId = null): array ``` -------------------------------- ### Retrieve extra product index settings Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Demonstrates how to fetch and parse extra product index settings from the configuration. ```php // Configuration value: {"customRanking": ["asc(price)"], "minProximity": 1} $extra = $configHelper->getExtraProductSettings($storeId); // Returns: ['customRanking' => ['asc(price)'], 'minProximity' => 1] ``` -------------------------------- ### Get conversion tracking mode Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the current conversion tracking mode. ```php public function getConversionAnalyticsMode(?int $storeId = null): string ``` -------------------------------- ### Get category attributes Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the list of additional category attributes to be indexed. ```php public function getCategoryAttributes(?int $storeId = null): array ``` -------------------------------- ### Constructor Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/EventProcessor.md Initializes the EventProcessor with required dependencies. ```php public function __construct( private InsightsClient $insightsClient, private StoreManagerInterface $storeManager, private ConfigHelper $configHelper ): void ``` -------------------------------- ### Product IndexBuilder Constructor Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/IndexBuilder.md Dependencies required for initializing the Product IndexBuilder service. ```php public function __construct( private ProductRecordBuilder $recordBuilder, private AlgoliaConnector $connector, private IndexOptionsBuilder $indexOptionsBuilder, private ConfigHelper $configHelper, private ProductCollectionProvider $collectionProvider, private ReplicaManager $replicaManager, // ... other dependencies ) ``` -------------------------------- ### Category Record Structure Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/README.md Example of the data structure for a category record indexed in Algolia. ```php [ 'objectID' => 'magento_category_5_1', 'name' => 'T-Shirts', 'path' => 'Clothing > T-Shirts', 'description' => '...', 'url' => 'https://example.com/clothing/t-shirts.html', 'product_count' => 42, 'level' => 2, '_store_id' => 1 ] ``` -------------------------------- ### Basic Initialization of SearchClientProvider Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/SearchClientProvider.md Inject the SearchClientProviderInterface into your class constructor to access store-specific Algolia clients. ```php clientProvider->getClient($storeId); $client->saveObjects('magento_products_store1', $products); } catch (AlgoliaException $e) { echo "Algolia error: " . $e->getMessage(); } } } ``` -------------------------------- ### Get write operation timeout Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the timeout setting for write operations in seconds. ```php public function getWriteTimeout(?int $storeId = null): int ``` -------------------------------- ### Get read operation timeout Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the timeout setting for read operations in seconds. ```php public function getReadTimeout(?int $storeId = null): int ``` -------------------------------- ### Process Product Batch via BatchQueueProcessor Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/BatchQueueProcessor.md Instantiate the product batch processor from the container and execute a batch update for specific product IDs. ```php $processor = $container->get( \Algolia\AlgoliaSearch\Service\Product\BatchQueueProcessor::class ); $processor->processBatch($storeId, [productId1, productId2]); ``` -------------------------------- ### Get maximum record size Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the maximum allowed record size in bytes. ```php public function getMaxRecordSize(?int $storeId = null): int ``` -------------------------------- ### Get category custom ranking Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the custom ranking attributes configured for categories. ```php public function getCategoryCustomRanking(?int $storeId = null): array ``` -------------------------------- ### Create Replicas During Index Build Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ReplicaManager.md Use createReplicas to initialize sorting replicas based on custom ranking configurations during a full index build. ```php optionsBuilder->build($storeId); // Build main index $this->buildMainIndex($indexOptions); // Create sorting replicas $sortConfigs = $this->getSortConfigurations($storeId); $this->replicaManager->createReplicas($indexOptions, $sortConfigs, true); } private function getSortConfigurations(int $storeId): array { $ranking = $this->configHelper->getProductCustomRanking($storeId); // Parse ranking config into sort configs return $this->parseRankingToSortConfigs($ranking); } } ``` -------------------------------- ### Get Algolia Client Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/AlgoliaConnector.md Retrieves an authenticated Algolia client instance for a specific store scope. ```php $client = $connector->getClient($storeId); ``` -------------------------------- ### Build Batch Records in PHP Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/RecordBuilder.md Iterates through a collection of products to build records, logging warnings for any individual failures without stopping the batch process. ```php public function buildBatch(int $storeId, array $products): array { $records = []; foreach ($products as $product) { try { $record = $this->recordBuilder->buildRecord($product); $records[] = $record; } catch (Exception $e) { $this->logger->warning("Skipped product {$product->getId()}: {$e->getMessage()}"); } } return $records; } ``` -------------------------------- ### Retrieve and inspect a job Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/types.md Demonstrates retrieving a job from the repository and accessing its properties. ```php $job = $jobRepository->get($jobId); echo $job->getClass(); // 'Algolia\AlgoliaSearch\Observer\ProductObserver' echo $job->getMethod(); // 'execute' echo $job->getStatus(); // 'pending' ``` -------------------------------- ### Get results per page Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the number of results displayed per page for pagination. ```php public function getNumberOfElementByPage(?int $storeId = null): int ``` -------------------------------- ### Build Records for IndexBuilder in PHP Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/RecordBuilder.md Shows the implementation of a product indexer class using RecordBuilder with exception handling for specific product states. ```php recordBuilder->buildRecord($product); } catch (ProductDeletedException|ProductOutOfStockException $e) { // Entity cannot be indexed - skip it return null; } } } ``` -------------------------------- ### Get category breadcrumb separator Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the separator string used for category breadcrumb paths. ```php public function getCategorySeparator(?int $storeId = null): string ``` -------------------------------- ### AlgoliaConnector SearchClient Integration Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/SearchClientProvider.md Demonstrates how to inject the SearchClientProvider into a service to retrieve a configured SearchClient instance. ```php public function __construct( private SearchClientProviderInterface $clientProvider, // ... other dependencies ) {} public function getClient(?int $storeId = null): SearchClient { return $this->clientProvider->getClient($storeId); } ``` -------------------------------- ### Get word removal strategy Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the strategy used for removing words when search results are empty. ```php public function shouldRemoveWordsIfNoResult(?int $storeId = null): bool|string ``` -------------------------------- ### Handle ProductOutOfStockException Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/errors.md Use this to handle out-of-stock products based on current inventory configuration settings. ```php try { $record = $recordBuilder->buildRecord($product); } catch (ProductOutOfStockException $e) { // Check configuration if ($configHelper->indexOutOfStockProducts()) { // Re-attempt with stock info included } else { $this->logger->info("Skipping out-of-stock product"); } } ``` -------------------------------- ### Handle ReplicaLimitExceededException Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ReplicaManager.md Demonstrates catching the replica limit exception and implementing a fallback strategy by limiting the number of configurations. ```php try { $replicaManager->createReplicas($options, $sortConfigs); } catch (ReplicaLimitExceededException $e) { $this->messageManager->addErrorMessage( "Cannot create all requested replicas: {$e->getMessage()}" ); // Fallback: create fewer replicas $limitedConfigs = array_slice($sortConfigs, 0, 5); $replicaManager->createReplicas($options, $limitedConfigs); } ``` -------------------------------- ### getExtraProductSettings Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves extra Algolia index settings for products as a JSON-parsed array. ```APIDOC ## getExtraProductSettings(?int $storeId) ### Description Retrieves extra Algolia index settings for products. Returns an array of settings defined in the configuration. ### Parameters - **storeId** (int) - Optional - The ID of the store to retrieve settings for. ### Returns - **array** - The parsed Algolia index settings. ``` -------------------------------- ### Handle RecordBuilder Exceptions in PHP Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/RecordBuilder.md Demonstrates catching specific product indexing exceptions to log events and skip records gracefully. ```php try { $record = $recordBuilder->buildRecord($product); } catch (ProductOutOfStockException $e) { $this->logger->info('Skipping out-of-stock product'); return null; } catch (ProductNotVisibleException $e) { $this->logger->debug('Skipping hidden product'); return null; } catch (Exception $e) { $this->logger->error('Failed to build record: ' . $e->getMessage()); throw $e; } ``` -------------------------------- ### Build Index Configuration Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/IndexBuilder.md Creates index configuration for a specific store, optionally including a suffix for temporary indexes. ```php public function build(int $storeId, ?string $suffix = null): IndexOptionsInterface ``` ```php $options = $indexOptionsBuilder->build($storeId, '_tmp'); // Returns IndexOptions with name 'magento_products_storeX_tmp' ``` -------------------------------- ### Configuration-Aware Integration Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/EventProcessor.md Handles checkout completion events based on the configured conversion analytics mode. ```php public function handleCheckoutComplete(Order $order): void { $mode = $this->configHelper->getConversionAnalyticsMode(); switch ($mode) { case ConversionAnalyticsMode::STANDARD: $this->trackStandardConversion($order); break; case ConversionAnalyticsMode::ADD_TO_CART: // Event already tracked at cart stage break; case ConversionAnalyticsMode::PURCHASE: $this->trackPurchase($order); break; } } private function trackPurchase(Order $order): void { try { $indexName = $this->indexNameFetcher->getIndexName('products', $order->getStoreId()); $this->eventProcessor ->setAuthenticatedUserToken($order->getCustomerId() ?? $this->getSessionId()) ->convertPurchase('Purchase', $indexName, $order); } catch (AlgoliaException $e) { $this->logger->error("Purchase tracking failed: {$e->getMessage()}"); } } ``` -------------------------------- ### Handle ProductNotVisibleException Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/errors.md Use this to handle products not visible individually, optionally checking configuration to allow indexing. ```php try { $record = $recordBuilder->buildRecord($product); } catch (ProductNotVisibleException $e) { // Handle based on configuration if ($configHelper->includeNonVisibleProducts()) { // Configuration allows non-visible products, re-attempt } else { $this->logger->debug("Skipping non-visible product"); } } ``` -------------------------------- ### Handle Indexing Exceptions Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/IndexBuilder.md Demonstrates catching entity-specific exceptions during the index building process. ```php try { $indexBuilder->buildIndex($storeId, [123, 456], null); } catch (ProductDeletedException $e) { $this->logger->warning('Product deleted: ' . $e->getMessage()); } catch (ProductOutOfStockException $e) { $this->logger->info('Product out of stock, skipped: ' . $e->getMessage()); } ``` -------------------------------- ### Run local verification commands Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/AGENTS.md Use these commands to perform syntax checks and validation on modified files without a full Magento environment. ```bash php -l ``` ```bash composer validate ``` ```bash magento2-lint ``` ```bash magento2-analyse ``` ```bash magento2-test ``` -------------------------------- ### Execute unit tests Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/AGENTS.md Run unit tests using the project's PHPUnit configuration. ```bash vendor/bin/phpunit -c dev/tests/unit/phpunit.xml.dist \ vendor/algolia/algoliasearch-magento-2/Test/Unit ``` -------------------------------- ### Build index settings with extra configuration Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Merges base index settings with extra settings retrieved from the ConfigHelper. ```php public function configureProductIndex(IndexOptionsInterface $options): array { $settings = [ 'searchableAttributes' => ['name', 'description', 'sku'], 'attributesForFaceting' => $this->configHelper->getCategoryAttributes(), 'customRanking' => $this->configHelper->getProductCustomRanking(), ]; // Merge extra settings from configuration $extra = $this->configHelper->getExtraProductSettings($options->getStoreId()); return array_merge($settings, $extra); } ``` -------------------------------- ### Handle ProductDeletedException Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/errors.md Use this to skip indexing for products that no longer exist in the database. ```php try { $record = $recordBuilder->buildRecord($product); } catch (ProductDeletedException $e) { // Product was deleted, skip it $this->logger->info("Skipping deleted product: {$e->getMessage()}"); $this->queueRepository->markProcessed($jobId); } ``` -------------------------------- ### getClient() Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/AlgoliaConnector.md Returns an authenticated Algolia client for the specified store. ```APIDOC ## getClient(?int $storeId) ### Description Returns an authenticated Algolia client for the specified store. ### Parameters - **$storeId** (?int) - Optional - Store ID (0 for default global scope) ### Returns - **SearchClient** - Authenticated client instance ### Throws - **AlgoliaException** - If credentials are invalid or API error occurs ``` -------------------------------- ### Handle UnknownSkuException Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/errors.md Use this to log warnings when a product SKU is not found or invalid during batch operations. ```php try { $record = $recordBuilder->buildRecord($product); } catch (UnknownSkuException $e) { $this->logger->warning("Product with invalid SKU: {$e->getMessage()}"); } ``` -------------------------------- ### SearchClientProvider Constructor Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/SearchClientProvider.md Constructor dependencies for the SearchClientProvider service. ```php public function __construct( private ConfigHelper $configHelper, private AlgoliaCredentialsManager $credentialsManager, private LoggerInterface $logger, private ManagerInterface $messageManager ): void ``` -------------------------------- ### getExtraSuggestionSettings Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves extra Algolia index settings for suggestions. ```APIDOC ## getExtraSuggestionSettings(?int $storeId) ### Description Retrieves extra Algolia index settings for suggestions. ### Parameters - **storeId** (int) - Optional - The ID of the store to retrieve settings for. ### Returns - **array** - The parsed Algolia index settings. ``` -------------------------------- ### Cleanup Replicas on Uninstall Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ReplicaManager.md Ensure all replicas are deleted before removing the main index to maintain clean state during module uninstallation. ```php public function cleanup(int $storeId): void { $indexOptions = $this->optionsBuilder->build($storeId); try { // Delete all replicas before deleting main index $this->replicaManager->deleteReplicas($indexOptions); // Delete main index $this->connector->deleteIndex($indexOptions); } catch (AlgoliaException $e) { $this->logger->error("Cleanup failed: {$e->getMessage()}"); } } ``` -------------------------------- ### IndexOptionsBuilder::build Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/IndexBuilder.md Creates index configuration for a specific store and optional suffix. ```APIDOC ## build ### Description Creates index configuration for a specific store and optional suffix (for temp indexes). ### Signature `public function build(int $storeId, ?string $suffix = null): IndexOptionsInterface` ### Parameters - **$storeId** (int) - Required - The ID of the store. - **$suffix** (string|null) - Optional - Suffix for temporary indexes. ### Returns - **IndexOptionsInterface** - The index configuration object. ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/BatchQueueProcessor.md Sets the configuration flag to enable debug logging for the processor. ```php ConfigHelper::LOGGING_ENABLED = true ``` -------------------------------- ### Process Queue Batch with IndexBuilder Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/IndexBuilder.md Handles batch indexing from the queue and updates the repository status based on success or failure. ```php public function processQueueBatch(int $storeId, ?array $entityIds = null): void { try { $this->indexBuilder->buildIndex($storeId, $entityIds, null); $this->queueRepository->markAsProcessed($entityIds); } catch (Exception $e) { $this->logger->error('Batch indexing failed', ['exception' => $e]); $this->queueRepository->markAsFailed($entityIds); } } ``` -------------------------------- ### Automatic Batching for Large Orders Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/EventProcessor.md Demonstrates how the processor automatically handles large orders by batching items into smaller event chunks. ```php // Order with 100 items $eventProcessor->convertPurchase('Purchase', $indexName, $order); // Internally creates 5 events (20 items each) and batches into 1 request ``` -------------------------------- ### Handle ProductReindexingException Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/errors.md Use this to log fatal reindexing errors and re-throw the exception to fail the batch process. ```php try { $record = $recordBuilder->buildRecord($product); } catch (ProductReindexingException $e) { // Fatal error, must be logged and investigated $this->logger->error("Product reindexing failed: {$e->getMessage()}", [ 'exception' => $e, 'productId' => $product->getId() ]); throw $e; // Re-throw to fail the batch } ``` -------------------------------- ### Indexing Configuration Methods Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Methods to check the status of various indexing features. ```php public function isIndexingEnabled(?int $storeId = null): bool ``` ```php public function isProductIndexingEnabled(?int $storeId = null): bool ``` ```php public function isCategoryIndexingEnabled(?int $storeId = null): bool ``` ```php public function isPageIndexingEnabled(?int $storeId = null): bool ``` ```php public function isQuerySuggestionsIndexingEnabled(?int $storeId = null): bool ``` -------------------------------- ### Handle ProductDisabledException Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/errors.md Use this to skip indexing for products that are disabled in the current store view. ```php try { $record = $recordBuilder->buildRecord($product); } catch (ProductDisabledException $e) { // Product disabled, skip indexing $this->logger->debug("Skipping disabled product {$product->getId()}"); } ``` -------------------------------- ### ConfigHelper Constructor Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Constructor for the ConfigHelper service, requiring various Magento interfaces and helper classes. ```php public function __construct( ScopeConfigInterface $scopeConfig, StoreManagerInterface $storeManager, GroupCollection $groupCollection, Currency $localeCurrency, DirCurrency $dirCurrency, CookieHelper $cookieHelper, WeeeHelper $weeeHelper, SerializerInterface $serializer, ProductRecordFieldsInterface $productRecordFields, ReplicaManagerInterface $replicaManager, GroupExcludedWebsiteRepositoryInterface $groupExcludedWebsiteRepository ): void ``` -------------------------------- ### Update Replicas on Configuration Change Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ReplicaManager.md Recreate replicas when custom ranking settings change to reflect updated sorting logic in the search index. ```php public function onCustomRankingChanged(int $storeId): void { $indexOptions = $this->optionsBuilder->build($storeId); // Delete old replicas $this->replicaManager->deleteReplicas($indexOptions); // Create new replicas with updated ranking $sortConfigs = $this->getSortConfigurations($storeId); $this->replicaManager->createReplicas($indexOptions, $sortConfigs, true); } ``` -------------------------------- ### Handle CategoryEmptyException Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/errors.md Verify if empty categories should be indexed based on configuration before skipping. ```php try { $record = $categoryRecordBuilder->buildRecord($category); } catch (CategoryEmptyException $e) { if ($configHelper->indexEmptyCategories()) { // Configuration allows, re-attempt } else { $this->logger->debug("Skipping empty category"); } } ``` -------------------------------- ### AlgoliaConnector Constructor Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/AlgoliaConnector.md The constructor requires various helper services for configuration, client management, and strategy resolution. ```php public function __construct( ConfigHelper $config, ManagerInterface $messageManager, ConsoleOutput $consoleOutput, SearchClientProviderInterface $clientProvider, IndexNameFetcher $indexNameFetcher, IndexOptionsBuilder $indexOptionsBuilder, SendStrategyResolver $sendStrategyResolver ): void ``` -------------------------------- ### Handle DiagnosticsException Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/errors.md Log warnings when system diagnostic collection fails. ```php try { $diagnostics = $diagnosticsCollector->collect(); } catch (DiagnosticsException $e) { $this->logger->warning("Diagnostic collection failed: {$e->getMessage()}"); } ``` -------------------------------- ### View Repository Structure Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/README.md Displays the directory layout of the algoliasearch-magento-2 project. ```text algoliasearch-magento-2/ ├── Api/ # Public interfaces and contracts │ ├── Builder/ # Index and record builders │ ├── Data/ # Data model interfaces │ ├── Insights/ # Analytics event processor │ ├── Product/ # Product-specific contracts │ ├── Processor/ # Queue processing │ ├── Console/ # Console commands │ └── ClientProviderInterface # Client factory ├── Service/ # Core services │ ├── AlgoliaConnector.php # Main API bridge │ ├── SearchClientProvider.php # Client factory │ ├── {Entity}/ # Entity-specific services │ │ ├── IndexBuilder.php │ │ ├── RecordBuilder.php │ │ └── BatchQueueProcessor.php │ └── ... ├── Helper/ # Helper utilities │ ├── ConfigHelper.php # Configuration access │ ├── Configuration/ # Scoped config helpers │ ├── Entity/ # Entity-specific helpers │ └── ... ├── Model/ # Data models │ ├── Data/ # Data model implementations │ ├── Indexer/ # Magento indexer integration │ ├── Observer/ # Event observers │ ├── Queue*.php # Queue models │ └── ... ├── Block/ # Frontend blocks ├── Controller/ # Backend/frontend controllers ├── Exception/ # Custom exception classes ├── Logger/ # Logging infrastructure ├── etc/ # Configuration │ ├── di.xml # Dependency injection │ ├── events.xml # Event definitions │ ├── system.xml # Admin configuration │ └── db_schema.xml # Database schema └── registration.php # Module registration ``` -------------------------------- ### setSettings() Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/AlgoliaConnector.md Update index settings in Algolia. ```APIDOC ## setSettings(IndexOptionsInterface $indexOptions, mixed $settings, bool $forwardToReplicas, bool $mergeSettings, string $mergeSettingsFrom) ### Description Update index settings in Algolia. ### Parameters - **$indexOptions** (IndexOptionsInterface) - Required - Index configuration - **$settings** (mixed) - Required - Settings array (searchable attributes, facets, etc.) - **$forwardToReplicas** (bool) - Optional - Forward settings to all replica indexes - **$mergeSettings** (bool) - Optional - Merge with existing settings instead of replace - **$mergeSettingsFrom** (string) - Optional - Source index to merge settings from ### Returns - **void** ### Throws - **AlgoliaException|NoSuchEntityException** - On failure ``` -------------------------------- ### Check indexing feature flags Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Validates whether product indexing is enabled and if non-visible products should be included. ```php public function shouldIndexProduct(Product $product, int $storeId): bool { if (!$this->configHelper->isIndexingEnabled($storeId)) { return false; } if (!$this->configHelper->isProductIndexingEnabled($storeId)) { return false; } if (!$product->isVisibleInCatalog() && !$this->configHelper->includeNonVisibleProducts($storeId)) { return false; } return true; } ``` -------------------------------- ### Settings Operations Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/SearchClientProvider.md Methods to manage index settings and configuration. ```APIDOC ## Settings Operations - **getSettings(string $indexName)**: array - Retrieve index settings. - **setSettings(string $indexName, array $settings, bool $forwardToReplicas = false)**: array - Update index settings. - **clearIndex(string $indexName)**: array - Clear an index. - **deleteIndex(string $indexName)**: array - Delete an index. ``` -------------------------------- ### convertPurchase() Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/EventProcessor.md Tracks a purchase conversion for all items in an order, automatically batching items as needed. ```APIDOC ## convertPurchase(string $eventName, string $indexName, Order $order) ### Description Track purchase conversion for all items in an order. Batches items efficiently (max 20 objects per event). ### Parameters - **$eventName** (string) - Required - Event name (e.g., 'Purchase') - **$indexName** (string) - Required - Algolia index name - **$order** (Order) - Required - Magento sales order ### Returns - **array** - Array of API responses (one per batch) ### Example ```php $responses = $eventProcessor->convertPurchase( 'Purchase', 'magento_products_store1', $order ); ``` ``` -------------------------------- ### Track conversion without search context in PHP Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/EventProcessor.md Use this method for tracking conversions from organic traffic or direct visits where no search query context is available. ```php public function convertedObjectIDs( string $eventName, string $indexName, array $objectIDs, array $requestOptions = [] ): array ``` ```php // Track product view from category page (not search) $eventProcessor->convertedObjectIDs( 'Product Viewed', 'magento_products_store1', ['123'] ); ``` -------------------------------- ### ConfigHelper Class Declaration Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md The base class definition for the ConfigHelper service. ```php namespace Algolia\AlgoliaSearch\Helper; class ConfigHelper { // Configuration constants and methods documented below } ``` -------------------------------- ### Declare processBatch Method Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/BatchQueueProcessor.md Method signature for processing queued indexing jobs. ```php public function processBatch(int $storeId, ?array $entityIds = null): void ``` -------------------------------- ### buildIndexFull(int $storeId, ?array $options) Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/IndexBuilder.md Performs a complete full reindex of all entities for a store using an atomic swap. ```APIDOC ## buildIndexFull(int $storeId, ?array $options) ### Description Performs a complete full reindex of all entities for a store. It creates a temporary index, populates it completely, and then atomically swaps it with the main index. ### Parameters - **$storeId** (int) - Required - Magento store ID - **$options** (array) - Optional - Additional options ### Returns - **void** ### Example ```php $indexBuilder->buildIndexFull($storeId); ``` ``` -------------------------------- ### Define IndexOptionsInterface Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/types.md Interface for managing index configuration including store ID, suffix, and temporary status. ```php interface IndexOptionsInterface { public const STORE_ID = 'store_id'; public const INDEX_SUFFIX = 'index_suffix'; public const IS_TMP = 'is_tmp'; public const INDEX_NAME = 'index_name'; public function getStoreId(): ?int; public function getIndexSuffix(): ?string; public function isTemporaryIndex(): bool; public function getIndexName(): ?string; public function setIndexName(string $indexName): void; } ``` -------------------------------- ### Index Operation Methods Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/SearchClientProvider.md Methods for checking index existence and retrieving index objects. ```php public function indexExists(string $indexName): bool public function getIndex(string $indexName): Index public function listIndices(): array ``` -------------------------------- ### Frontend Configuration Flow Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/doc/ARCHITECTURE.md Visual representation of how search configuration is passed from Magento admin settings to client-side JavaScript. ```text Admin config (system.xml) -> ConfigHelper + specialized helpers -> Block/Configuration.php serializes to a JS config object -> autocomplete.js, instantsearch.js, insights.js, recommend.js -> client-side rendering (no server-side search results) ``` -------------------------------- ### Manual Event Tracking Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/EventProcessor.md Tracks custom conversions by manually specifying product IDs and the target index. ```php public function trackCustomConversion(array $productIds, int $storeId): void { try { $indexName = $this->indexNameFetcher->getIndexName('products', $storeId); $this->eventProcessor ->setAnonymousUserToken($this->getSessionId()) ->convertedObjectIDs('Custom Conversion', $indexName, $productIds); } catch (AlgoliaException $e) { $this->logger->error("Failed to track custom conversion: {$e->getMessage()}"); } } ``` -------------------------------- ### getProductAttributes(?int $storeId = null) Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Retrieves the list of additional product attributes to index. ```APIDOC ## getProductAttributes(?int $storeId = null) ### Description Get array of additional product attributes to index. ### Parameters #### Path Parameters - **storeId** (int) - Optional - The store ID to retrieve configuration for. ### Returns - **array** - Attribute codes (Default: []) ``` -------------------------------- ### Configuration-Aware Error Handling Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/errors.md Implement conditional logic to retry indexing operations based on specific configuration settings when validation exceptions occur. ```php public function indexProduct(Product $product): ?array { try { return $this->recordBuilder->buildRecord($product); } catch (ProductOutOfStockException $e) { if ($this->configHelper->indexOutOfStockProducts()) { // Retry without stock check return $this->buildWithoutStockCheck($product); } return null; } catch (ProductNotVisibleException $e) { if ($this->configHelper->includeNonVisibleProducts()) { // Retry allowing non-visible return $this->buildAllowingNonVisible($product); } return null; } } ``` -------------------------------- ### Settings Operation Methods Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/SearchClientProvider.md Methods for managing index settings, clearing, and deleting indices. ```php public function getSettings(string $indexName): array public function setSettings(string $indexName, array $settings, bool $forwardToReplicas = false): array public function clearIndex(string $indexName): array public function deleteIndex(string $indexName): array ``` -------------------------------- ### ReplicaManager Constructor Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ReplicaManager.md Constructor for the ReplicaManager service. ```php public function __construct( private AlgoliaConnector $connector, private ConfigHelper $configHelper, private IndexNameFetcher $indexNameFetcher, private Logger $logger, private ReplicaNameGenerator $replicaNameGenerator ): void ``` -------------------------------- ### Observer Pattern for Add to Cart Tracking Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/EventProcessor.md Implements automatic tracking for cart additions, checking configuration settings before processing. ```php configHelper->isClickConversionAnalyticsEnabled()) { return; } try { $this->eventProcessor ->setAuthenticatedUserToken($this->getCustomerId()) ->convertAddToCart('Add to Cart', 'magento_products_store1', $cartItem, $queryID); } catch (Exception $e) { $this->logger->warning("Event tracking failed: {$e->getMessage()}"); // Don't fail checkout due to analytics } } private function getCustomerId(): string { return $this->customerSession->getCustomerId() ?? $this->getSessionId(); } } ``` -------------------------------- ### Product Indexing Operations Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/IndexBuilder.md Methods for performing incremental updates, full reindexing, and temporary indexing for products. ```php // Index recent product changes $productIndexBuilder->buildIndex($storeId, null, null); // Full reindex of all products $productIndexBuilder->buildIndexFull($storeId); // Index specific products to temp index (pre-swap) $productIndexBuilder->buildIndex($storeId, [1, 2, 3], ['tmp' => true]); ``` -------------------------------- ### Search products via AlgoliaConnector Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/README.md Executes a search query using the AlgoliaConnector service. Returns an empty array if an exception occurs during the query process. ```php connector->query( $this->buildSearchQuery($storeId, $query) ); } catch (Exception $e) { return []; } } } ``` -------------------------------- ### Handle Unexpected Exceptions Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/BatchQueueProcessor.md Use this catch-all block to log critical, unknown errors that require investigation during batch processing. ```php catch (Exception $e) { // Unknown error - must be investigated $this->logger->critical("Unexpected error in batch processing", [ 'exception' => $e, 'store_id' => $storeId, 'entity_ids' => $entityIds ]); throw $e; } ``` -------------------------------- ### Execute integration tests Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/AGENTS.md Run integration tests within a Magento environment, requiring specific Algolia environment variables. ```bash cd /dev/tests/integration ../../../vendor/bin/phpunit ../../../vendor/algolia/algoliasearch-magento-2/Test/Integration/ ``` -------------------------------- ### Conditional processing based on configuration Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ConfigHelper.md Uses indexing and logging flags to control job processing flow. ```php public function processQueue(int $storeId, array $jobIds): void { if (!$this->configHelper->isIndexingEnabled($storeId)) { return; // Skip if disabled } foreach ($jobIds as $jobId) { try { $this->processJob($jobId); } catch (Exception $e) { if ($this->configHelper->isLoggingEnabled($storeId)) { $this->logger->error("Job {$jobId} failed: {$e->getMessage()}"); } } } } ``` -------------------------------- ### Configure Babel for JavaScript Bundling Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/README.md Use this configuration when applying the Babel transpiler to source code for advanced RequireJS optimization. ```json { "presets": [ [ "@babel/preset-env", { "exclude": ["@babel/plugin-transform-template-literals"] } ], ["minify", { "builtIns": false, "mangle": false }] ], "comments": false } ``` -------------------------------- ### Process Queue via CLI Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/BatchQueueProcessor.md Execute pending queue jobs using Magento CLI commands. ```bash # Process all pending queue jobs for all stores php bin/magento algolia:queue:process # Process queue in loop (better for production) php bin/magento algolia:queue:process --loop ``` -------------------------------- ### Define ConversionAnalyticsMode source model Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/types.md Source model class defining available conversion analytics modes. ```php class ConversionAnalyticsMode { public const DISABLED = 'disabled'; public const STANDARD = 'standard'; public const ADD_TO_CART = 'addToCart'; public const PURCHASE = 'purchase'; } ``` -------------------------------- ### getClient Method Signature Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/SearchClientProvider.md Method signature for retrieving an authenticated Algolia search client. ```php public function getClient(?int $storeId = null): SearchClient ``` -------------------------------- ### createReplicas(IndexOptionsInterface $indexOptions, array $sortAttributes, bool $forwardToReplicas) Source: https://github.com/algolia/algoliasearch-magento-2/blob/main/_autodocs/api-reference/ReplicaManager.md Creates or updates replica indices with specified sorting configurations. ```APIDOC ## createReplicas(IndexOptionsInterface $indexOptions, array $sortAttributes, bool $forwardToReplicas) ### Description Create or update replica indices with specified sorting configurations. ### Parameters - **$indexOptions** (IndexOptionsInterface) - Required - Main index configuration - **$sortAttributes** (array) - Required - Array of sort attribute configurations - **$forwardToReplicas** (bool) - Optional (Default: false) - Forward index settings changes to replicas ### Returns - **void** ### Throws - **AlgoliaException** on API failure - **ReplicaLimitExceededException** if too many replicas would be created ### Example ```php $sortConfigs = [ ['attribute' => 'price', 'direction' => 'asc'], ['attribute' => 'price', 'direction' => 'desc'], ['attribute' => 'name', 'direction' => 'asc'], ['attribute' => 'popularity', 'direction' => 'desc'], ]; $replicaManager->createReplicas($indexOptions, $sortConfigs, true); ``` ```