Magento 2: How to re-index Programmatically?

Magento 2 Reindex Programmatically

Let’s see how we can re-index programmatically in this post. If you want to invalidate the indexer programmatically, Please check out the post – https://sbdevblog.com/magento-2-how-to-invalidate-indexer-programmatically/

We are very often required to re-index using code as per our requirement in the custom module. I will explain how we can achieve this using code.

I assume that you have already created a custom module with the appropriate vendor name. As usual, the vendor name in my case is SbDevBlog.

I have created an IndexerService Class in my module. You will need to create a similar class inside your Vendor/ModuleName/Services directory and extend it in your class or inject it into your class constructor.

Magento 2: How to re-index Programmatically?

<?php
/**
 * @copyright Copyright (c) sbdevblog (http://www.sbdevblog.com)
 */

namespace SbDevBlog\Indexer\Services;

use Magento\Framework\Indexer\IndexerInterface;
use Magento\Indexer\Model\IndexerFactory;
use Magento\Indexer\Model\Indexer\Collection;
use Psr\Log\LoggerInterface;

class indexerService
{
    private const CATALOG_CATEGORY_PROD_INDXER = "catalog_category_product";
    /**
     * @var IndexerInterface
     */
    private IndexerInterface $indexer;

    /**
     * @var Collection
     */
    private Collection $collection;

    /**
     * @var LoggerInterface
     */
    private LoggerInterface $logger;

    /**
     * @var IndexerFactory
     */
    private IndexerFactory $indexerFactory;

    /**
     * Constructor For Service
     *
     * @param IndexerInterface $indexer
     * @param LoggerInterface $logger
     */
    public function __construct(
        IndexerInterface $indexer,
        Collection       $collection,
        IndexerFactory $indexerFactory,
        LoggerInterface  $logger
    )
    {
        $this->indexer = $indexer;
        $this->collection = $collection;
        $this->logger = $logger;
        $this->indexerFactory = $indexerFactory;
    }

    /**
     * Re-index by id
     *
     * @param string $indexerKey
     * @return bool
     */
    public function reIndexById(string $indexerKey): bool
    {
        if (!$indexerKey) {
            return false;
        }
        try {
            $indexer = $this->getIndexerById($indexerKey);
            $indexer->reindexAll();
            return true;
        } catch (\InvalidArgumentException|\Exception $e) {
            $this->logger->error($e->getMessage());
        }
        return false;
    }

    /**
     * Get Indexer by id
     *
     * @param string $indexerKey
     * @return IndexerInterface
     */
    private function getIndexerById(string $indexerKey): IndexerInterface
    {
        return $this->indexer->load($indexerKey);
    }

    /**
     * Reindex all indxer
     * @return void
     */
    public function reindexAllIndexer()
    {
        $indexes = $this->collection->getAllIds();
        try {
            foreach ($indexes as $index) {
                $indexer = $this->indexerFactory->create()->load($index);

                $indexer->reindexAll();

            }
        }catch (Exception $e) {
            $this->logger->error($e->getMessage());
        }
    }

    /**
     * ReIndex Category Product Indexer
     *
     * @return void
     */
    public function reIndexCatProdId()
    {
        $indexer = $this->getIndexerById(self::CATALOG_CATEGORY_PROD_INDXER);
        try {
            $indexer->reindexAll();
        } catch (Exception $e) {
            $this->logger->error($e->getMessage());
        }
    }
}

That’s it, the function given below is responsible for re-indexing based on the indexer id provided dynamically as a parameter in the function.

    /**
     * Get Indexer by id
     *
     * @param string $indexerKey
     * @return IndexerInterface
     */
    private function getIndexerById(string $indexerKey): IndexerInterface
    {
        return $this->indexer->load($indexerKey);
    }

That’s it, the function given below is responsible for re-indexing all indexes.

/**
     * Reindex all indxer
     * @return void
     */
    public function reindexAllIndexer()
    {
        $indexes = $this->collection->getAllIds();
        try {
            foreach ($indexes as $index) {
                $indexer = $this->indexerFactory->create()->load($index);

                $indexer->reindexAll();

            }
        }catch (Exception $e) {
            $this->logger->error($e->getMessage());
        }
    }

reIndexCatProdId() Function is responsible for re-indexing of catalog category product index.

Thanks for reading Magento 2: How to re-index Programmatically?

Use the comment box for your suggestions and feedback.
Download Source Code

Note: Please verify the code of this blog and the relevant git repository before using it in production.
sb dev blog adobe commece Magento 2

🙂 HAPPY CODING 🙂

2 thoughts on “Magento 2: How to re-index Programmatically?

Leave a Reply

Your email address will not be published. Required fields are marked *