Magento 2 automatically create index
In this tutorial I show you how to automatically create index for Magento 2. Since Magento 2 it is not more possible to create indexes from your backend. There are way to do it by command line, but for most modules (for example an import) you have to create index programmatically. I show you how.
Magento 2 automatically create index
The following lines of code creates all Magento indexes:
1 2 3 4 5 6 7 8 | //reindex $indexerFactory = $objectManager->get('Magento\Indexer\Model\IndexerFactory'); $indexerIds = array('catalogrule_rule'); foreach ($indexerIds as $indexerId) { $indexer = $indexerFactory->create(); $indexer->load($indexerId); $indexer->reindexAll(); } |
This sample code shows you how to only reindex catalogrule_rule index. For reindex you need IndexerFactory. You can get this Factory like every other Factory under Magento 2 with an objectManager. I created an array indexerIds with all ids of indexers that I want to reindex. Reindex itself is done in one simpe foreach loop. If you need more and other indexers, feel free to change this array.
List of all available indexes
A list of all possible indexes can be found in Magento documentation. There are listed the following indexer ids:
- catalog_category_product
- catalog_product_category
- catalog_product_price
- catalog_product_attribute
- cataloginventory_stock
- catalogrule_rule
- catalogrule_product
- catalogsearch_fulltext
How to reindex by command line
The preferred solution to reindex all indexes or only one index is to do it from command line. Magento offers you a tool for this. You can not reindex from Magento backend as you may know from Magento 1. Here is how you can do this:
Basically there are 2 major commands:
- indexer:status
shows you a list of all indexes and a status. There are two possibilities: “Ready” or “Reindex required”. You only need to call a reindex if it is required. - indexer:reindex
with this you can reindex all indexes. As you can see on my screenshot, it only takes some seconds. If there is a lot to do re indexing can be quite time consuming. You can also reindex specific indexes by calling its name for example indexer:reindex catalog_category_product
Conclusion
You can programmatically create indexes by using IndexerFactory. Sometimes you have to do this, especially if you create an importer module.
Hello,
I have upgraded my magento version from 2.1.0 to 2.1.7
Earlier the reindex time for Product Categories was 00:03:08 and now it has increased to 01:12:00
Can anyone help me understand the reason behind this?
If you have a dev system, you can try to truncate category index table and reindex. I have not discovered this issue. Does the reindex last always over one minute or only the first time?