How to Reindexing Programmatically In Magento 2?

  • Posted by Envision Ecommerce
  • /
  • April 18, 2017

Use 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;
}
 // you can call this function to do reindexing
public function reIndexing(){
   $indexerCollection = $this->_indexerCollectionFactory->create();
   $ids = $indexerCollection->getAllIds();
   foreach ($ids as $id) {
   $idx = $this->_indexerFactory->create()->load($id);
   $idx->reindexAll($id); // this reindexes all
   //$idx->reindexRow($id); // or you can use reindexRow according to your need
}

If you still have any query regarding this “How to” or would like to add some suggestions to this solution, let us know your feedback or query at [email protected], and don’t forget to share this “How to” blog with your fellow Magento 2 users!