Back to Top

Reindexing programmatically in magento 2

Updated 28 March 2024

Reindexing programmatically in magento 2.

Reindex is the process of updating the transformed data as the data changes. E.g.: when updating a product price the data should be reindexed to be correctly displayed on the frontend.

In this article we will learn how to reindexing through code in magento 2.

You can write the below code in any class according to your need :

/**
 * @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
}

That’s all in this article, hope it will help you to call custom block and links inside footer. Try the above code and if you have any issue just comment below. 🙂

Searching for an experienced
Magento 2 Company ?
Find out More
. . .

Leave a Comment

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


2 comments

  • Gediminas K.
  • Hervé Guétin
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home