Reindexing Programmatically In Magento 2 Simplified
The post is all about performing reindexing programmatically in Magento 2.
The way in which Magento transforms the data such as products and categories in order to improve the performance of the frontend is indexing. Whenever there is any change in the data from the backend, i.e., product price updates, a product added under a particular category, etc., the transformed data has to be updated or say reindexed.
This is because the Magento 2 database structure is complicated with multiple database tables that store the prices, users, etc. In order to reflect the changes in the frontend instantly, you need to reindex the data with indexers.
If a developer does not perform Magento 2 reindexing, the changes implemented would take longer to load, possibly annoying the visitor and abandoning your store.
As we do not want this to happen, here’s how to programmatically reindex in Magento 2:
Method to do Reindexing Programmatically In Magento 2:
Create Data.php in app/code/[Vendor]/[Module]/Helper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
namespace [Vendor]\[Module]\Helper; use Magento\Framework\App\Helper\AbstractHelper use Magento\Framework\App\Helper\Context; use Magento\Indexer\Model\IndexerFactory; use Magento\Indexer\Model\Indexer\Collection; class Data extends AbstractHelper { private $indexFactory; private $indexCollection; public function __construct( Context $context, IndexerFactory $indexFactory, Collection $indexCollection, ) { parent::__construct($context); $this->indexCollection = $indexCollection; $this->indexFactory = $indexFactory; } public function manuallIndexing() { $indexes = $this->indexCollection->getAllIds(); foreach ($indexes as $index){ $indexFactory = $this->indexFactory->create()->load($index); $indexFactory->reindexAll($index); $indexFactory->reindexRow($index); } } } |
Now, you can use this helper class method for indexing.
That’s it.
Please use the Comments section below if you have any doubts related to Magento 2 reindexing. I’ll be happy to help.
Feel free to share the solution with fellow developers via social media.
Related Post:
Thank you.
Also Read:
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
2 Comments
How can we use this code?
Hello,
If you require to reindex programmatically, place the code in a file where you are making the changes.
Thank you.