Magento Reindex Programmatically

The Magento indexing mechanism is one of the core functionalities that improve a site performance. However, when programming bulk imports of data it is ideal to stop the indexing until the import is completed. For two reasons, first the indexing will slow the process, as on each line of data imported a reindex of data will be performed. Secondly it can generate errors due to the amount of data that is constantly changing.

Switching off Indexes

The indexes can be switched off by disabling the reindexing on save option.

Given that the index process is referenced by the variable $process to disable the reindex on save the command is

  1. $process->setMode(Mage_Index_Model_Process::MODE_MANUAL)->save();

Switching on Indexes

The indexes can be switched on by enabling the reindexing on save option.

Given that the index process is referenced by the variable $process to disable the reindex on save the command is

  1. $process->setMode(Mage_Index_Model_Process::MODE_REAL_TIME)->save();

Reindex All

In Magento Admin site it is common to select all the processes and run a full reindex process. To replicate this process in programming terms, one needs to iterate over all index processes and execute the command reindexEverything().

  1. $indexingProcesses = Mage::getSingleton('index/indexer')->getProcessesCollection(); 
  2. foreach ($indexingProcesses as $process) {
  3.       $process->reindexEverything();
  4. }

Running a specific index

Indexes can be loaded using either the process ID or the process code using the functions:

by ID:

  1. $process = Mage::getSingleton('index/indexer')->getProcessById();

by CODE:

  1. $process = Mage::getSingleton('index/indexer')->getProcessByCode(<process_code>);

The process code and ID can be found by checking the table index_process. The Magento provided indexes normally have the following ID and code.

Process NameIDCode
Product Attributes1catalog_product_attribute
Product Prices2catalog_product_price
Catalog URL Rewrites3catalog_url
Product Flat Data4catalog_product_flat
Category Flat Data5catalog_category_flat
Category Products6catalog_category_product
Catalog Search Index7catalogsearch_stock
Stock Status8cataloginventory_stock
Tag Aggregation Data9tag_summary

 

References: