How to Reindex Programmatically In Magento 2

In this article, I am going to show you some of the code which will be helpful to reindex in Magento 2 programmatically.

In the below example, I will be using both Dependency Injection (DI) and Object Manager to reindex in Magento 2 programmatically.

I have also posted an article for Reindex via Command Line in Magento 2

Using Dependency Injection (DI)

The following lines of code are used to reindex all the Magento 2 indexes using dependency injection, Use the below code in any class for reindexing in Magento2.

/**
 * @var \Magento\Indexer\Model\IndexerFactory
 */
protected $_indexerFactory;
 
/**
 * @var \Magento\Indexer\Model\Indexer\CollectionFactory
 */
protected $_indexerCollectionFactory;
 
public function __construct(
    \Magento\Indexer\Model\IndexerFactory $indexerFactory,
    \Magento\Indexer\Model\Indexer\CollectionFactory $indexerCollectionFactory
){
    $this->_indexerFactory = $indexerFactory;
    $this->_indexerCollectionFactory = $indexerCollectionFactory;
}

public function reIndexing(){
    $indexerCollection = $this->_indexerCollectionFactory->create();
    $allIds = $indexerCollection->getAllIds();
 
    foreach ($allIds as $id) {
        $indexer = $this->_indexerFactory->create()->load($id);
        $indexer->reindexAll();
    }
}

Using Object Manager

The following lines of code are used to reindex all the Magento 2 indexes using object manager,

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$indexerCollectionFactory = $objectManager->get("\Magento\Indexer\Model\Indexer\CollectionFactory");
$indexerFactory = $objectManager->get("\Magento\Indexer\Model\IndexerFactory");
 
$indexerCollection = $indexerCollectionFactory->create();
$allIds = $indexerCollection->getAllIds();
foreach ($allIds as $id) {
    $indexer = $indexerFactory->create()->load($id);
    $indexer->reindexAll();
}

The following lines of code are used to reindex specific index by id,

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$indexerFactory = $objectManager->get('Magento\Indexer\Model\IndexerFactory');

$indexer = $indexerFactory->create();
$indexer->load('catalogrule_rule');
$indexer->reindexAll();
List of all available indexes

Here the list of all available indexes in Magento 2,

  • catalog_category_product
  • catalog_product_category
  • catalog_product_price
  • catalog_product_attribute
  • cataloginventory_stock
  • catalogrule_rule
  • catalogrule_product
  • catalogsearch_fulltext

A list of all possible indexes can be found in Magento documentation.

Hope this helps.

Leave a Reply

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