How to Reindexing Programmatically In Magento 2?

  • author-img Nidhi Arora
  • 4 years
  • 328 views

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!

Download Blog

ENQUIRY

Ready to Get started

Communication is the key for us to understand each other. Allow us to understand
your requirements or queries. Present us with an opportunity to serve you.

Fill out the form and out team will get back to you
within 24 hours

    Head Office

    1250 Pittsford Victor Road Ste 310
    Pittsford, NY 14534

    Development Center

    Plot no. 10, Rajiv Gandhi
    Chandigarh Technology Park