Magento 2How To GuideAugust 28, 2020

How to Reindex Magento 2 Programmatically?

How to Reindex Magento 2 Programmatically?

What is Reindexing in Magento 2?

Magento has an efficient but a complex database architecture with lots of tables holding various types of data. It has almost 40 tables for the products and categories alone. Magento database is not how most databases worked in the past i.e. one table containing product information, another containing category information and maybe another one linking these two together. Instead, Magento splits data up into many sub tables. This means that when some information is updated, all the tables containing that data should be updated simultaneously so that users can have the latest data. To do this, Magento collects all of the relevant information and puts them into a selection of smaller tables. This is called indexing. Indexing improves the performance of the store’s front end. It helps customers quickly retrieve the information on the front end.

Reindex Magento 2 Programmatically

Reindexing in Magento 2 is normally done automatically. Magento starts a reindex on save actions. You can also manually reindex Magento 2 via command line or schedule it to take place at specific times. In this article, we are going to see how to reindex programmatically. To do this, you can add the following lines of code in any class or extension.


namespace Vendor\ModuleName\Controller;
class Reindex 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;


// call this function to do reindexing
public function Myreindexer()


$indexerCollection = $this->indexCollection->create();
$indexids = $indexerCollection->getAllIds();

foreach ($indexids as $indexid)


$indexidarray = $this->indexFactory->create()->load($indexid);

//If you want to reindex all.

//If you want to reindex one by one.


That’s pretty much it for this article. If you face any issue or have any questions regarding the above code, contact our expert Magento 2 consultants. Related Articles: