Magento 2 – programmatically reindexing
In this tutorial I show you how you can manually or programmatically reindexing your shop. This is sometimes necessary if you run a full product import with all data (products, categories, customers). Especially if you want to create configurable products and do some creation logic based on simple product attributes.
Magento 2 – programmatically reindexing
The following sample code shows you a function, that starts reindexing for specified indexes. If you run reindexAll(), all given indexes are recomputed if necessary. It is a good starting point to build an own index updating script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public function reindexAll() { $indexerFactory = $this->_objectManager->get('Magento\Indexer\Model\IndexerFactory'); $indexerIds = array( 'catalog_category_product', 'catalog_product_category', 'catalog_product_price', 'catalog_product_attribute', 'cataloginventory_stock', 'catalogrule_product', 'catalogsearch_fulltext', ); foreach ($indexerIds as $indexerId) { echo " create index: ".$indexerId."\n"; $indexer = $indexerFactory->create(); $indexer->load($indexerId); $indexer->reindexAll(); } } |
We need a indexerFactory to get an index by its name. This example gets it from objectManager. As always, it is a far better solution to inject Magento\Indexer\Model\IndexerFactory in your class! For the simplicity of a small PHP script, we will only use objectManager for this. Then we create an array of all indexes we want to reindex. You have to name it correctly. You will find the correct name and a list of all indexes in Mangento 2 indexer_state table.
The last step is a foreach loop which reindexes each individual index. As you can see, you will use a factory to get an indexer object and its load method to load a specific index by its name. A call to reindexAll() method does the trick. It starts reindexing process, which can last a while.
Conclusion
It is quite easy to programmatically reindexing in Magento 2. There is no option in your adminhtml for this, so if you are creating an import module you may need to force reindexing by your script to see product changes in you shop. If you have a lot of products, reindexing can last a long time, so it is often a good idea to plan it for a night batch job.