How to Reindexing Programmatically In Magento 2?

  • author-img Nidhi Arora
  • 8 years

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 sales@envisionecommerce.com, and don’t forget to share this “How to” blog with your fellow Magento 2 users!

Download Blog

ENQUIRY

Ready to Get Started?

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

    Head Office

    815 Brazos St STE 500, Austin,
    TX 78701, USA