How to perform Reindexing Programmatically in Magento 2

How to perform reindexing programmatically in Magento 2

Indexing is all about how Magento alters data, such as products and categories, to enhance the performance of your store front-end. Once you make any changes to backend or code all your data must be refreshed or updated. Because Magento owns very complex database architecture that contains many database tables to store information like catalog data, prices, users, and stores and to get an instant effect in frontend one must have to reindex all this information in special database tables using indexers. Even making a small change in price or URL requires reindexing of data to get an effect. Instead of manually indexing, using a small piece of code in an extension helps you to perform reindexing programmatically in Magento 2. Here is how to do it.

<?php
namespace Vendor\Extension\Controller;
 
class Myactions extends \Magento\Framework\App\Action\Action
{
	protected $indexFactory;
   protected $indexCollection;
 
   public function __construct(
    \Magento\Indexer\Model\IndexerFactory $indexFactory,
	\Magento\Indexer\Model\Indexer\CollectionFactory $indexCollection
   ){
        $this->indexFactory = $indexFactory;
        $this->indexCollection = $indexCollection;
	}
 
   public function Mycustomaction()
   {
  	$indexerCollection = $this->indexCollection->create();
  	$indexids = $indexerCollection->getAllIds();
 
  	foreach ($indexids as $indexid)
  	{
     	$indexidarray = $this->indexFactory->create()->load($indexid);
 
     	//If you want reindex all use this code.
         $indexidarray->reindexAll($indexid);
 
     	//If you want to reindex one by one, use this code
         $indexidarray->reindexRow($indexid);
  	}
   }
}

That’s it! You can also read our blog to know “How to clean and flush cache programmatically in Magento 2” we have a blog for that too. That’s it for today, Let us know if you are facing an issue while implementing using this code by commenting below.

Happy Indexing!

Quick Cache and Reindex

Previous Article

MageComp Partners with FME Extensions

Next Article

How to use Section.xml file in Magento 2

Write a Comment

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨