cronjob: How to reindex only what is needed Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Create a cronjobWhat is wrong with my Cpanel cronjob configuration?Never ending CronjobHow do I set up my cronjob?Problem with reindex catalog_product_pricesMagento2 - Cronjob issueMagento 2 for cronjobIndexer, Reindex ALL Magento2Magento 1.9 how to set products to out of stock if quantity is 0 using php?Magento 2: Reindex script does not work with cronjob

Determine whether an integer is a palindrome

Why is there so little support for joining EFTA in the British parliament?

What does 丫 mean? 丫是什么意思?

New Order #6: Easter Egg

Did pre-Columbian Americans know the spherical shape of the Earth?

calculator's angle answer for trig ratios that can work in more than 1 quadrant on the unit circle

Is the Mordenkainen's Sword spell underpowered?

Keep at all times, the minus sign above aligned with minus sign below

What is "Lambda" in Heston's original paper on stochastic volatility models?

Why are two-digit numbers in Jonathan Swift's "Gulliver's Travels" (1726) written in "German style"?

Marquee sign letters

malloc in main() or malloc in another function: allocating memory for a struct and its members

An isoperimetric-type inequality inside a cube

Meaning of 境 in その日を境に

How can I list files in reverse time order by a command and pass them as arguments to another command?

How to name indistinguishable henchmen in a screenplay?

How can I prevent/balance waiting and turtling as a response to cooldown mechanics

Does the main washing effect of soap come from foam?

Is this Kuo-toa homebrew race balanced?

Did any compiler fully use 80-bit floating point?

Short story about astronauts fertilizing soil with their own bodies

First paper to introduce the "principal-agent problem"

.bashrc alias for a command with fixed second parameter

Diophantine equation 3^a+1=3^b+5^c



cronjob: How to reindex only what is needed



Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?Create a cronjobWhat is wrong with my Cpanel cronjob configuration?Never ending CronjobHow do I set up my cronjob?Problem with reindex catalog_product_pricesMagento2 - Cronjob issueMagento 2 for cronjobIndexer, Reindex ALL Magento2Magento 1.9 how to set products to out of stock if quantity is 0 using php?Magento 2: Reindex script does not work with cronjob



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








8















We got a server which has 5 separately shops on it. Some are practically inactive. Some are daily active.
To decrease the server load. We changed the index from automatic to manual. Then we set a cronjob every 6 hours.
I found enough examples of reindexing all.



We run something like this now:

Shop1: 0 0,6,12,18 * * * php -f /shell/indexer.php reindexall

Shop2: 0 1,7,13,19 * * * php -f /shell/indexer.php reindexall

and so on, to avoid overlap.



Right now the inactive shops also reindex every 6 hours where none is needed. Is there a way to only reindex what is needed with a cronjob?



Or are we doing is wrong altogether?










share|improve this question






























    8















    We got a server which has 5 separately shops on it. Some are practically inactive. Some are daily active.
    To decrease the server load. We changed the index from automatic to manual. Then we set a cronjob every 6 hours.
    I found enough examples of reindexing all.



    We run something like this now:

    Shop1: 0 0,6,12,18 * * * php -f /shell/indexer.php reindexall

    Shop2: 0 1,7,13,19 * * * php -f /shell/indexer.php reindexall

    and so on, to avoid overlap.



    Right now the inactive shops also reindex every 6 hours where none is needed. Is there a way to only reindex what is needed with a cronjob?



    Or are we doing is wrong altogether?










    share|improve this question


























      8












      8








      8


      2






      We got a server which has 5 separately shops on it. Some are practically inactive. Some are daily active.
      To decrease the server load. We changed the index from automatic to manual. Then we set a cronjob every 6 hours.
      I found enough examples of reindexing all.



      We run something like this now:

      Shop1: 0 0,6,12,18 * * * php -f /shell/indexer.php reindexall

      Shop2: 0 1,7,13,19 * * * php -f /shell/indexer.php reindexall

      and so on, to avoid overlap.



      Right now the inactive shops also reindex every 6 hours where none is needed. Is there a way to only reindex what is needed with a cronjob?



      Or are we doing is wrong altogether?










      share|improve this question
















      We got a server which has 5 separately shops on it. Some are practically inactive. Some are daily active.
      To decrease the server load. We changed the index from automatic to manual. Then we set a cronjob every 6 hours.
      I found enough examples of reindexing all.



      We run something like this now:

      Shop1: 0 0,6,12,18 * * * php -f /shell/indexer.php reindexall

      Shop2: 0 1,7,13,19 * * * php -f /shell/indexer.php reindexall

      and so on, to avoid overlap.



      Right now the inactive shops also reindex every 6 hours where none is needed. Is there a way to only reindex what is needed with a cronjob?



      Or are we doing is wrong altogether?







      cron indexer






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 23 '17 at 12:37









      Community

      1




      1










      asked Feb 11 '14 at 9:37









      janwjanw

      5702720




      5702720




















          5 Answers
          5






          active

          oldest

          votes


















          3














          What you want is to create a shell cli script, and use that to determine if a index requires a re-index.



          Have a look at the scripts in the shell folder (log.php will do fine) as an example on how to make such a script.



          The script you create would then check the status of the index, and only re-index if it is in a status that requires indexing.



          I generally create my custom shell scripts in a folder called /scripts, as I don't like to pollute the core folder shell with my custom code.



          To this effect, I have a abstract class that I base all my scripts off, and it contains code that allows me to easily re-index indexers, if they require indexing.



          here is my abstract class:



          /**
          * Abstracted functions for scripts
          *
          * @category ProxiBlue
          * @package Scripts
          * @author Lucas van Staden (sales@proxiblue.com.au)
          * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
          *
          */
          require_once dirname(__FILE__) . '/../shell/abstract.php';

          class Mage_Shell_Scripts_Abstract extends Mage_Shell_Abstract

          public $_doReindexFlag = false;

          public function run()

          die('Please implement a run function inyour script');


          /**
          * Get the category model
          * @return Object
          */
          public function getCatalogModel()
          return Mage::getModel('catalog/category');


          /**
          * Reindex given indexers.
          * Tests if indexer actually needs re-index, and is not in manual state before it does index.
          *
          * @param array $reIndex
          */
          public function reindex(array $reIndex)

          foreach ($reIndex as $indexerId)
          $process = $this->_getIndexer()->getProcessByCode($indexerId);
          if ($process->getStatus() == Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX && $process->getMode() != Mage_Index_Model_Process::MODE_MANUAL)
          try
          echo "Reindexing: " . $process->getIndexerCode();
          $process->reindexEverything();
          catch (Exception $e)
          mage::logException("$indexer Indexer had issues. $e->getMessage()");





          /**
          * Get Indexer instance
          *
          * @return Mage_Index_Model_Indexer
          */
          private function _getIndexer()
          return Mage::getSingleton('index/indexer');


          /**
          * Returns a list of cache types.
          * @return void
          */
          public function getInvalidateCache()
          $invalidTypes = $this->_getInvalidatedTypes();
          $result = array();
          foreach($invalidTypes as $cache)
          if ($cache->status == 1)
          $result[] = $cache;


          return $result;


          /**
          * Gets a list of invalidated cache types that should be refreshed.
          * @return array Array of invalidated types.
          */
          private function _getInvalidatedTypes()
          return Mage::getModel('core/cache')->getInvalidatedTypes();
          //return $this->_getCacheTypes();


          /**
          * Gets Magento cache types.
          * @return
          */
          private function _getCacheTypes()
          //return Mage::helper('core')->getCacheTypes();
          return Mage::getModel('core/cache')->getTypes();





          Then a class that is based off that, that calls a re-index, after some work was done.



          require_once dirname(__FILE__) . '/abstract.php';

          class Mage_Shell_setCategoryStatus extends Mage_Shell_Scripts_Abstract

          public $_doReindexFlag = true;
          public function run()

          /** code stripped out as not warrented for this answer **/

          if ($this->_doReindexFlag)
          $this->reindex(array('catalog_product_flat',
          'catalog_category_flat',
          'catalog_category_product',
          'cataloginventory_stock',
          'catalogsearch_fulltext',
          ));





          $shell = new Mage_Shell_setCategoryStatus();
          $shell->run();




          share

























          • I have to say the answer given by @Flyingmana is in fact far smarter than my own ;)

            – ProxiBlue
            Mar 14 '14 at 12:26


















          6














          What I know, the Index is something global, so a reindex always covers all Stores/Websites of one Magento.



          But, Magento has some functionality you will like. While "update on Save" does the updates to index instant, the "manual update" puts the same "updates" into a queue, which you can trigger later.



          For this, you will need to write your own shell script or cron job



           $pCollection = Mage::getSingleton('index/indexer')->getProcessesCollection();

          foreach ($pCollection as $process)
          $process->indexEvents();



          I will not explain the basics of the process models, simply have a look at the indexEvents function, it takes the entries of the queue and updates them. But be careful, the URL Index can be a bit slow. But that's another problem.






          share|improve this answer




















          • 1





            Interesting solution, I didn't know that the events are saved when "manual update" is activated. This would allow indexing only the changed data.

            – Andreas von Studnitz
            Feb 18 '14 at 21:29


















          0














          To reindex the processes we require their ids.

          For default magento there are 9 processes to reindex, numbered 1 to 9.



          $ids = array(1,2,3,4,5,6,7,8,9);


          Sometimes there are processes from our custom modules that also require reindexing
          We need to add those ids to our existing array of ids, To know the id of process, just hover on each process in your
          admin panel-> System-> Index Management



          You will get a url : admin/process/some_id/...... this id corresponds to the process



          $ids = array(1,2,3,4,5,6,7,8,9,390,391,478);
          foreach($ids as $id)

          //load each process through its id
          try

          $process = Mage::getModel('index/process')->load($id);
          $process->reindexAll();
          echo "Indexing for Process ID # ".$id." Done<br />";

          catch(Exception $e)

          echo $e->getMessage();







          share|improve this answer

























          • This doesn't answer my question how to change the cronjob. Also this reindexes everything. I only want to reindex the parts that are changed.

            – janw
            Feb 11 '14 at 12:37



















          0














          <?php
          // this loops through all indexes and processes those that say they require reindexing

          include_once '../app/Mage.php';

          $mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
          $mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';

          $app = Mage::app ( $mageRunCode, $mageRunType );
          for($i=3; $i<=9; $i++)
          $process = Mage::getSingleton('index/indexer')->getProcessById($i);
          $state = $process->getStatus();
          // echo '<pre>'.$process->getData('indexer_code').': '.htmlentities(print_r($process->getStatus(),true)).'</pre>';
          if($process->getStatus() == 'require_reindex')
          $process->reindexEverything();


          ?>





          share|improve this answer
































            0














            I liked Amit Bera's answer best - but modified placing the id's in an array and most importantly arranged for smoothest operation.
            If you run straight through by the numbers re-indexing one index table can cause another to become invalid.
            I.E. Index product_flat table then price can cause product flat table to become invalid and need re-indexing.



            <?php
            // this loops through all indexes and processes those that say they require reindexing

            include_once 'app/Mage.php';

            $mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
            $mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';

            $app = Mage::app ( $mageRunCode, $mageRunType );

            $ids = array(13,9,8,7,6,1,2,3,5,4);

            foreach($ids as $id)
            $process = Mage::getSingleton('index/indexer')->getProcessById($id);
            $state = $process->getStatus();
            // echo '<pre>'.$process->getData('indexer_code').': '.htmlentities(print_r($process->getStatus(),true)).'</pre>';
            if($process->getStatus() == 'require_reindex')
            $process->reindexEverything();







            share|improve this answer




















            • 2





              FYI its @jim who answerd not amit.

              – dh47
              Jun 4 '15 at 11:50











            Your Answer








            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "479"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f14828%2fcronjob-how-to-reindex-only-what-is-needed%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            5 Answers
            5






            active

            oldest

            votes








            5 Answers
            5






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3














            What you want is to create a shell cli script, and use that to determine if a index requires a re-index.



            Have a look at the scripts in the shell folder (log.php will do fine) as an example on how to make such a script.



            The script you create would then check the status of the index, and only re-index if it is in a status that requires indexing.



            I generally create my custom shell scripts in a folder called /scripts, as I don't like to pollute the core folder shell with my custom code.



            To this effect, I have a abstract class that I base all my scripts off, and it contains code that allows me to easily re-index indexers, if they require indexing.



            here is my abstract class:



            /**
            * Abstracted functions for scripts
            *
            * @category ProxiBlue
            * @package Scripts
            * @author Lucas van Staden (sales@proxiblue.com.au)
            * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
            *
            */
            require_once dirname(__FILE__) . '/../shell/abstract.php';

            class Mage_Shell_Scripts_Abstract extends Mage_Shell_Abstract

            public $_doReindexFlag = false;

            public function run()

            die('Please implement a run function inyour script');


            /**
            * Get the category model
            * @return Object
            */
            public function getCatalogModel()
            return Mage::getModel('catalog/category');


            /**
            * Reindex given indexers.
            * Tests if indexer actually needs re-index, and is not in manual state before it does index.
            *
            * @param array $reIndex
            */
            public function reindex(array $reIndex)

            foreach ($reIndex as $indexerId)
            $process = $this->_getIndexer()->getProcessByCode($indexerId);
            if ($process->getStatus() == Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX && $process->getMode() != Mage_Index_Model_Process::MODE_MANUAL)
            try
            echo "Reindexing: " . $process->getIndexerCode();
            $process->reindexEverything();
            catch (Exception $e)
            mage::logException("$indexer Indexer had issues. $e->getMessage()");





            /**
            * Get Indexer instance
            *
            * @return Mage_Index_Model_Indexer
            */
            private function _getIndexer()
            return Mage::getSingleton('index/indexer');


            /**
            * Returns a list of cache types.
            * @return void
            */
            public function getInvalidateCache()
            $invalidTypes = $this->_getInvalidatedTypes();
            $result = array();
            foreach($invalidTypes as $cache)
            if ($cache->status == 1)
            $result[] = $cache;


            return $result;


            /**
            * Gets a list of invalidated cache types that should be refreshed.
            * @return array Array of invalidated types.
            */
            private function _getInvalidatedTypes()
            return Mage::getModel('core/cache')->getInvalidatedTypes();
            //return $this->_getCacheTypes();


            /**
            * Gets Magento cache types.
            * @return
            */
            private function _getCacheTypes()
            //return Mage::helper('core')->getCacheTypes();
            return Mage::getModel('core/cache')->getTypes();





            Then a class that is based off that, that calls a re-index, after some work was done.



            require_once dirname(__FILE__) . '/abstract.php';

            class Mage_Shell_setCategoryStatus extends Mage_Shell_Scripts_Abstract

            public $_doReindexFlag = true;
            public function run()

            /** code stripped out as not warrented for this answer **/

            if ($this->_doReindexFlag)
            $this->reindex(array('catalog_product_flat',
            'catalog_category_flat',
            'catalog_category_product',
            'cataloginventory_stock',
            'catalogsearch_fulltext',
            ));





            $shell = new Mage_Shell_setCategoryStatus();
            $shell->run();




            share

























            • I have to say the answer given by @Flyingmana is in fact far smarter than my own ;)

              – ProxiBlue
              Mar 14 '14 at 12:26















            3














            What you want is to create a shell cli script, and use that to determine if a index requires a re-index.



            Have a look at the scripts in the shell folder (log.php will do fine) as an example on how to make such a script.



            The script you create would then check the status of the index, and only re-index if it is in a status that requires indexing.



            I generally create my custom shell scripts in a folder called /scripts, as I don't like to pollute the core folder shell with my custom code.



            To this effect, I have a abstract class that I base all my scripts off, and it contains code that allows me to easily re-index indexers, if they require indexing.



            here is my abstract class:



            /**
            * Abstracted functions for scripts
            *
            * @category ProxiBlue
            * @package Scripts
            * @author Lucas van Staden (sales@proxiblue.com.au)
            * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
            *
            */
            require_once dirname(__FILE__) . '/../shell/abstract.php';

            class Mage_Shell_Scripts_Abstract extends Mage_Shell_Abstract

            public $_doReindexFlag = false;

            public function run()

            die('Please implement a run function inyour script');


            /**
            * Get the category model
            * @return Object
            */
            public function getCatalogModel()
            return Mage::getModel('catalog/category');


            /**
            * Reindex given indexers.
            * Tests if indexer actually needs re-index, and is not in manual state before it does index.
            *
            * @param array $reIndex
            */
            public function reindex(array $reIndex)

            foreach ($reIndex as $indexerId)
            $process = $this->_getIndexer()->getProcessByCode($indexerId);
            if ($process->getStatus() == Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX && $process->getMode() != Mage_Index_Model_Process::MODE_MANUAL)
            try
            echo "Reindexing: " . $process->getIndexerCode();
            $process->reindexEverything();
            catch (Exception $e)
            mage::logException("$indexer Indexer had issues. $e->getMessage()");





            /**
            * Get Indexer instance
            *
            * @return Mage_Index_Model_Indexer
            */
            private function _getIndexer()
            return Mage::getSingleton('index/indexer');


            /**
            * Returns a list of cache types.
            * @return void
            */
            public function getInvalidateCache()
            $invalidTypes = $this->_getInvalidatedTypes();
            $result = array();
            foreach($invalidTypes as $cache)
            if ($cache->status == 1)
            $result[] = $cache;


            return $result;


            /**
            * Gets a list of invalidated cache types that should be refreshed.
            * @return array Array of invalidated types.
            */
            private function _getInvalidatedTypes()
            return Mage::getModel('core/cache')->getInvalidatedTypes();
            //return $this->_getCacheTypes();


            /**
            * Gets Magento cache types.
            * @return
            */
            private function _getCacheTypes()
            //return Mage::helper('core')->getCacheTypes();
            return Mage::getModel('core/cache')->getTypes();





            Then a class that is based off that, that calls a re-index, after some work was done.



            require_once dirname(__FILE__) . '/abstract.php';

            class Mage_Shell_setCategoryStatus extends Mage_Shell_Scripts_Abstract

            public $_doReindexFlag = true;
            public function run()

            /** code stripped out as not warrented for this answer **/

            if ($this->_doReindexFlag)
            $this->reindex(array('catalog_product_flat',
            'catalog_category_flat',
            'catalog_category_product',
            'cataloginventory_stock',
            'catalogsearch_fulltext',
            ));





            $shell = new Mage_Shell_setCategoryStatus();
            $shell->run();




            share

























            • I have to say the answer given by @Flyingmana is in fact far smarter than my own ;)

              – ProxiBlue
              Mar 14 '14 at 12:26













            3












            3








            3







            What you want is to create a shell cli script, and use that to determine if a index requires a re-index.



            Have a look at the scripts in the shell folder (log.php will do fine) as an example on how to make such a script.



            The script you create would then check the status of the index, and only re-index if it is in a status that requires indexing.



            I generally create my custom shell scripts in a folder called /scripts, as I don't like to pollute the core folder shell with my custom code.



            To this effect, I have a abstract class that I base all my scripts off, and it contains code that allows me to easily re-index indexers, if they require indexing.



            here is my abstract class:



            /**
            * Abstracted functions for scripts
            *
            * @category ProxiBlue
            * @package Scripts
            * @author Lucas van Staden (sales@proxiblue.com.au)
            * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
            *
            */
            require_once dirname(__FILE__) . '/../shell/abstract.php';

            class Mage_Shell_Scripts_Abstract extends Mage_Shell_Abstract

            public $_doReindexFlag = false;

            public function run()

            die('Please implement a run function inyour script');


            /**
            * Get the category model
            * @return Object
            */
            public function getCatalogModel()
            return Mage::getModel('catalog/category');


            /**
            * Reindex given indexers.
            * Tests if indexer actually needs re-index, and is not in manual state before it does index.
            *
            * @param array $reIndex
            */
            public function reindex(array $reIndex)

            foreach ($reIndex as $indexerId)
            $process = $this->_getIndexer()->getProcessByCode($indexerId);
            if ($process->getStatus() == Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX && $process->getMode() != Mage_Index_Model_Process::MODE_MANUAL)
            try
            echo "Reindexing: " . $process->getIndexerCode();
            $process->reindexEverything();
            catch (Exception $e)
            mage::logException("$indexer Indexer had issues. $e->getMessage()");





            /**
            * Get Indexer instance
            *
            * @return Mage_Index_Model_Indexer
            */
            private function _getIndexer()
            return Mage::getSingleton('index/indexer');


            /**
            * Returns a list of cache types.
            * @return void
            */
            public function getInvalidateCache()
            $invalidTypes = $this->_getInvalidatedTypes();
            $result = array();
            foreach($invalidTypes as $cache)
            if ($cache->status == 1)
            $result[] = $cache;


            return $result;


            /**
            * Gets a list of invalidated cache types that should be refreshed.
            * @return array Array of invalidated types.
            */
            private function _getInvalidatedTypes()
            return Mage::getModel('core/cache')->getInvalidatedTypes();
            //return $this->_getCacheTypes();


            /**
            * Gets Magento cache types.
            * @return
            */
            private function _getCacheTypes()
            //return Mage::helper('core')->getCacheTypes();
            return Mage::getModel('core/cache')->getTypes();





            Then a class that is based off that, that calls a re-index, after some work was done.



            require_once dirname(__FILE__) . '/abstract.php';

            class Mage_Shell_setCategoryStatus extends Mage_Shell_Scripts_Abstract

            public $_doReindexFlag = true;
            public function run()

            /** code stripped out as not warrented for this answer **/

            if ($this->_doReindexFlag)
            $this->reindex(array('catalog_product_flat',
            'catalog_category_flat',
            'catalog_category_product',
            'cataloginventory_stock',
            'catalogsearch_fulltext',
            ));





            $shell = new Mage_Shell_setCategoryStatus();
            $shell->run();




            share















            What you want is to create a shell cli script, and use that to determine if a index requires a re-index.



            Have a look at the scripts in the shell folder (log.php will do fine) as an example on how to make such a script.



            The script you create would then check the status of the index, and only re-index if it is in a status that requires indexing.



            I generally create my custom shell scripts in a folder called /scripts, as I don't like to pollute the core folder shell with my custom code.



            To this effect, I have a abstract class that I base all my scripts off, and it contains code that allows me to easily re-index indexers, if they require indexing.



            here is my abstract class:



            /**
            * Abstracted functions for scripts
            *
            * @category ProxiBlue
            * @package Scripts
            * @author Lucas van Staden (sales@proxiblue.com.au)
            * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
            *
            */
            require_once dirname(__FILE__) . '/../shell/abstract.php';

            class Mage_Shell_Scripts_Abstract extends Mage_Shell_Abstract

            public $_doReindexFlag = false;

            public function run()

            die('Please implement a run function inyour script');


            /**
            * Get the category model
            * @return Object
            */
            public function getCatalogModel()
            return Mage::getModel('catalog/category');


            /**
            * Reindex given indexers.
            * Tests if indexer actually needs re-index, and is not in manual state before it does index.
            *
            * @param array $reIndex
            */
            public function reindex(array $reIndex)

            foreach ($reIndex as $indexerId)
            $process = $this->_getIndexer()->getProcessByCode($indexerId);
            if ($process->getStatus() == Mage_Index_Model_Process::STATUS_REQUIRE_REINDEX && $process->getMode() != Mage_Index_Model_Process::MODE_MANUAL)
            try
            echo "Reindexing: " . $process->getIndexerCode();
            $process->reindexEverything();
            catch (Exception $e)
            mage::logException("$indexer Indexer had issues. $e->getMessage()");





            /**
            * Get Indexer instance
            *
            * @return Mage_Index_Model_Indexer
            */
            private function _getIndexer()
            return Mage::getSingleton('index/indexer');


            /**
            * Returns a list of cache types.
            * @return void
            */
            public function getInvalidateCache()
            $invalidTypes = $this->_getInvalidatedTypes();
            $result = array();
            foreach($invalidTypes as $cache)
            if ($cache->status == 1)
            $result[] = $cache;


            return $result;


            /**
            * Gets a list of invalidated cache types that should be refreshed.
            * @return array Array of invalidated types.
            */
            private function _getInvalidatedTypes()
            return Mage::getModel('core/cache')->getInvalidatedTypes();
            //return $this->_getCacheTypes();


            /**
            * Gets Magento cache types.
            * @return
            */
            private function _getCacheTypes()
            //return Mage::helper('core')->getCacheTypes();
            return Mage::getModel('core/cache')->getTypes();





            Then a class that is based off that, that calls a re-index, after some work was done.



            require_once dirname(__FILE__) . '/abstract.php';

            class Mage_Shell_setCategoryStatus extends Mage_Shell_Scripts_Abstract

            public $_doReindexFlag = true;
            public function run()

            /** code stripped out as not warrented for this answer **/

            if ($this->_doReindexFlag)
            $this->reindex(array('catalog_product_flat',
            'catalog_category_flat',
            'catalog_category_product',
            'cataloginventory_stock',
            'catalogsearch_fulltext',
            ));





            $shell = new Mage_Shell_setCategoryStatus();
            $shell->run();





            share













            share


            share








            edited Feb 18 at 4:47









            Teja Bhagavan Kollepara

            2,99241949




            2,99241949










            answered Feb 11 '14 at 13:36









            ProxiBlueProxiBlue

            8,87832653




            8,87832653












            • I have to say the answer given by @Flyingmana is in fact far smarter than my own ;)

              – ProxiBlue
              Mar 14 '14 at 12:26

















            • I have to say the answer given by @Flyingmana is in fact far smarter than my own ;)

              – ProxiBlue
              Mar 14 '14 at 12:26
















            I have to say the answer given by @Flyingmana is in fact far smarter than my own ;)

            – ProxiBlue
            Mar 14 '14 at 12:26





            I have to say the answer given by @Flyingmana is in fact far smarter than my own ;)

            – ProxiBlue
            Mar 14 '14 at 12:26













            6














            What I know, the Index is something global, so a reindex always covers all Stores/Websites of one Magento.



            But, Magento has some functionality you will like. While "update on Save" does the updates to index instant, the "manual update" puts the same "updates" into a queue, which you can trigger later.



            For this, you will need to write your own shell script or cron job



             $pCollection = Mage::getSingleton('index/indexer')->getProcessesCollection();

            foreach ($pCollection as $process)
            $process->indexEvents();



            I will not explain the basics of the process models, simply have a look at the indexEvents function, it takes the entries of the queue and updates them. But be careful, the URL Index can be a bit slow. But that's another problem.






            share|improve this answer




















            • 1





              Interesting solution, I didn't know that the events are saved when "manual update" is activated. This would allow indexing only the changed data.

              – Andreas von Studnitz
              Feb 18 '14 at 21:29















            6














            What I know, the Index is something global, so a reindex always covers all Stores/Websites of one Magento.



            But, Magento has some functionality you will like. While "update on Save" does the updates to index instant, the "manual update" puts the same "updates" into a queue, which you can trigger later.



            For this, you will need to write your own shell script or cron job



             $pCollection = Mage::getSingleton('index/indexer')->getProcessesCollection();

            foreach ($pCollection as $process)
            $process->indexEvents();



            I will not explain the basics of the process models, simply have a look at the indexEvents function, it takes the entries of the queue and updates them. But be careful, the URL Index can be a bit slow. But that's another problem.






            share|improve this answer




















            • 1





              Interesting solution, I didn't know that the events are saved when "manual update" is activated. This would allow indexing only the changed data.

              – Andreas von Studnitz
              Feb 18 '14 at 21:29













            6












            6








            6







            What I know, the Index is something global, so a reindex always covers all Stores/Websites of one Magento.



            But, Magento has some functionality you will like. While "update on Save" does the updates to index instant, the "manual update" puts the same "updates" into a queue, which you can trigger later.



            For this, you will need to write your own shell script or cron job



             $pCollection = Mage::getSingleton('index/indexer')->getProcessesCollection();

            foreach ($pCollection as $process)
            $process->indexEvents();



            I will not explain the basics of the process models, simply have a look at the indexEvents function, it takes the entries of the queue and updates them. But be careful, the URL Index can be a bit slow. But that's another problem.






            share|improve this answer















            What I know, the Index is something global, so a reindex always covers all Stores/Websites of one Magento.



            But, Magento has some functionality you will like. While "update on Save" does the updates to index instant, the "manual update" puts the same "updates" into a queue, which you can trigger later.



            For this, you will need to write your own shell script or cron job



             $pCollection = Mage::getSingleton('index/indexer')->getProcessesCollection();

            foreach ($pCollection as $process)
            $process->indexEvents();



            I will not explain the basics of the process models, simply have a look at the indexEvents function, it takes the entries of the queue and updates them. But be careful, the URL Index can be a bit slow. But that's another problem.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 4 mins ago









            Andhi Irawan

            3961720




            3961720










            answered Feb 11 '14 at 22:30









            FlyingmanaFlyingmana

            5,17632062




            5,17632062







            • 1





              Interesting solution, I didn't know that the events are saved when "manual update" is activated. This would allow indexing only the changed data.

              – Andreas von Studnitz
              Feb 18 '14 at 21:29












            • 1





              Interesting solution, I didn't know that the events are saved when "manual update" is activated. This would allow indexing only the changed data.

              – Andreas von Studnitz
              Feb 18 '14 at 21:29







            1




            1





            Interesting solution, I didn't know that the events are saved when "manual update" is activated. This would allow indexing only the changed data.

            – Andreas von Studnitz
            Feb 18 '14 at 21:29





            Interesting solution, I didn't know that the events are saved when "manual update" is activated. This would allow indexing only the changed data.

            – Andreas von Studnitz
            Feb 18 '14 at 21:29











            0














            To reindex the processes we require their ids.

            For default magento there are 9 processes to reindex, numbered 1 to 9.



            $ids = array(1,2,3,4,5,6,7,8,9);


            Sometimes there are processes from our custom modules that also require reindexing
            We need to add those ids to our existing array of ids, To know the id of process, just hover on each process in your
            admin panel-> System-> Index Management



            You will get a url : admin/process/some_id/...... this id corresponds to the process



            $ids = array(1,2,3,4,5,6,7,8,9,390,391,478);
            foreach($ids as $id)

            //load each process through its id
            try

            $process = Mage::getModel('index/process')->load($id);
            $process->reindexAll();
            echo "Indexing for Process ID # ".$id." Done<br />";

            catch(Exception $e)

            echo $e->getMessage();







            share|improve this answer

























            • This doesn't answer my question how to change the cronjob. Also this reindexes everything. I only want to reindex the parts that are changed.

              – janw
              Feb 11 '14 at 12:37
















            0














            To reindex the processes we require their ids.

            For default magento there are 9 processes to reindex, numbered 1 to 9.



            $ids = array(1,2,3,4,5,6,7,8,9);


            Sometimes there are processes from our custom modules that also require reindexing
            We need to add those ids to our existing array of ids, To know the id of process, just hover on each process in your
            admin panel-> System-> Index Management



            You will get a url : admin/process/some_id/...... this id corresponds to the process



            $ids = array(1,2,3,4,5,6,7,8,9,390,391,478);
            foreach($ids as $id)

            //load each process through its id
            try

            $process = Mage::getModel('index/process')->load($id);
            $process->reindexAll();
            echo "Indexing for Process ID # ".$id." Done<br />";

            catch(Exception $e)

            echo $e->getMessage();







            share|improve this answer

























            • This doesn't answer my question how to change the cronjob. Also this reindexes everything. I only want to reindex the parts that are changed.

              – janw
              Feb 11 '14 at 12:37














            0












            0








            0







            To reindex the processes we require their ids.

            For default magento there are 9 processes to reindex, numbered 1 to 9.



            $ids = array(1,2,3,4,5,6,7,8,9);


            Sometimes there are processes from our custom modules that also require reindexing
            We need to add those ids to our existing array of ids, To know the id of process, just hover on each process in your
            admin panel-> System-> Index Management



            You will get a url : admin/process/some_id/...... this id corresponds to the process



            $ids = array(1,2,3,4,5,6,7,8,9,390,391,478);
            foreach($ids as $id)

            //load each process through its id
            try

            $process = Mage::getModel('index/process')->load($id);
            $process->reindexAll();
            echo "Indexing for Process ID # ".$id." Done<br />";

            catch(Exception $e)

            echo $e->getMessage();







            share|improve this answer















            To reindex the processes we require their ids.

            For default magento there are 9 processes to reindex, numbered 1 to 9.



            $ids = array(1,2,3,4,5,6,7,8,9);


            Sometimes there are processes from our custom modules that also require reindexing
            We need to add those ids to our existing array of ids, To know the id of process, just hover on each process in your
            admin panel-> System-> Index Management



            You will get a url : admin/process/some_id/...... this id corresponds to the process



            $ids = array(1,2,3,4,5,6,7,8,9,390,391,478);
            foreach($ids as $id)

            //load each process through its id
            try

            $process = Mage::getModel('index/process')->load($id);
            $process->reindexAll();
            echo "Indexing for Process ID # ".$id." Done<br />";

            catch(Exception $e)

            echo $e->getMessage();








            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 11 '14 at 11:43









            janw

            5702720




            5702720










            answered Feb 11 '14 at 9:57









            Deepak MallahDeepak Mallah

            1,24921425




            1,24921425












            • This doesn't answer my question how to change the cronjob. Also this reindexes everything. I only want to reindex the parts that are changed.

              – janw
              Feb 11 '14 at 12:37


















            • This doesn't answer my question how to change the cronjob. Also this reindexes everything. I only want to reindex the parts that are changed.

              – janw
              Feb 11 '14 at 12:37

















            This doesn't answer my question how to change the cronjob. Also this reindexes everything. I only want to reindex the parts that are changed.

            – janw
            Feb 11 '14 at 12:37






            This doesn't answer my question how to change the cronjob. Also this reindexes everything. I only want to reindex the parts that are changed.

            – janw
            Feb 11 '14 at 12:37












            0














            <?php
            // this loops through all indexes and processes those that say they require reindexing

            include_once '../app/Mage.php';

            $mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
            $mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';

            $app = Mage::app ( $mageRunCode, $mageRunType );
            for($i=3; $i<=9; $i++)
            $process = Mage::getSingleton('index/indexer')->getProcessById($i);
            $state = $process->getStatus();
            // echo '<pre>'.$process->getData('indexer_code').': '.htmlentities(print_r($process->getStatus(),true)).'</pre>';
            if($process->getStatus() == 'require_reindex')
            $process->reindexEverything();


            ?>





            share|improve this answer





























              0














              <?php
              // this loops through all indexes and processes those that say they require reindexing

              include_once '../app/Mage.php';

              $mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
              $mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';

              $app = Mage::app ( $mageRunCode, $mageRunType );
              for($i=3; $i<=9; $i++)
              $process = Mage::getSingleton('index/indexer')->getProcessById($i);
              $state = $process->getStatus();
              // echo '<pre>'.$process->getData('indexer_code').': '.htmlentities(print_r($process->getStatus(),true)).'</pre>';
              if($process->getStatus() == 'require_reindex')
              $process->reindexEverything();


              ?>





              share|improve this answer



























                0












                0








                0







                <?php
                // this loops through all indexes and processes those that say they require reindexing

                include_once '../app/Mage.php';

                $mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
                $mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';

                $app = Mage::app ( $mageRunCode, $mageRunType );
                for($i=3; $i<=9; $i++)
                $process = Mage::getSingleton('index/indexer')->getProcessById($i);
                $state = $process->getStatus();
                // echo '<pre>'.$process->getData('indexer_code').': '.htmlentities(print_r($process->getStatus(),true)).'</pre>';
                if($process->getStatus() == 'require_reindex')
                $process->reindexEverything();


                ?>





                share|improve this answer















                <?php
                // this loops through all indexes and processes those that say they require reindexing

                include_once '../app/Mage.php';

                $mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
                $mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';

                $app = Mage::app ( $mageRunCode, $mageRunType );
                for($i=3; $i<=9; $i++)
                $process = Mage::getSingleton('index/indexer')->getProcessById($i);
                $state = $process->getStatus();
                // echo '<pre>'.$process->getData('indexer_code').': '.htmlentities(print_r($process->getStatus(),true)).'</pre>';
                if($process->getStatus() == 'require_reindex')
                $process->reindexEverything();


                ?>






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Oct 30 '14 at 19:25









                Amit Bera

                60.2k1678178




                60.2k1678178










                answered Oct 30 '14 at 19:05









                jrossijrossi

                1




                1





















                    0














                    I liked Amit Bera's answer best - but modified placing the id's in an array and most importantly arranged for smoothest operation.
                    If you run straight through by the numbers re-indexing one index table can cause another to become invalid.
                    I.E. Index product_flat table then price can cause product flat table to become invalid and need re-indexing.



                    <?php
                    // this loops through all indexes and processes those that say they require reindexing

                    include_once 'app/Mage.php';

                    $mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
                    $mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';

                    $app = Mage::app ( $mageRunCode, $mageRunType );

                    $ids = array(13,9,8,7,6,1,2,3,5,4);

                    foreach($ids as $id)
                    $process = Mage::getSingleton('index/indexer')->getProcessById($id);
                    $state = $process->getStatus();
                    // echo '<pre>'.$process->getData('indexer_code').': '.htmlentities(print_r($process->getStatus(),true)).'</pre>';
                    if($process->getStatus() == 'require_reindex')
                    $process->reindexEverything();







                    share|improve this answer




















                    • 2





                      FYI its @jim who answerd not amit.

                      – dh47
                      Jun 4 '15 at 11:50















                    0














                    I liked Amit Bera's answer best - but modified placing the id's in an array and most importantly arranged for smoothest operation.
                    If you run straight through by the numbers re-indexing one index table can cause another to become invalid.
                    I.E. Index product_flat table then price can cause product flat table to become invalid and need re-indexing.



                    <?php
                    // this loops through all indexes and processes those that say they require reindexing

                    include_once 'app/Mage.php';

                    $mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
                    $mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';

                    $app = Mage::app ( $mageRunCode, $mageRunType );

                    $ids = array(13,9,8,7,6,1,2,3,5,4);

                    foreach($ids as $id)
                    $process = Mage::getSingleton('index/indexer')->getProcessById($id);
                    $state = $process->getStatus();
                    // echo '<pre>'.$process->getData('indexer_code').': '.htmlentities(print_r($process->getStatus(),true)).'</pre>';
                    if($process->getStatus() == 'require_reindex')
                    $process->reindexEverything();







                    share|improve this answer




















                    • 2





                      FYI its @jim who answerd not amit.

                      – dh47
                      Jun 4 '15 at 11:50













                    0












                    0








                    0







                    I liked Amit Bera's answer best - but modified placing the id's in an array and most importantly arranged for smoothest operation.
                    If you run straight through by the numbers re-indexing one index table can cause another to become invalid.
                    I.E. Index product_flat table then price can cause product flat table to become invalid and need re-indexing.



                    <?php
                    // this loops through all indexes and processes those that say they require reindexing

                    include_once 'app/Mage.php';

                    $mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
                    $mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';

                    $app = Mage::app ( $mageRunCode, $mageRunType );

                    $ids = array(13,9,8,7,6,1,2,3,5,4);

                    foreach($ids as $id)
                    $process = Mage::getSingleton('index/indexer')->getProcessById($id);
                    $state = $process->getStatus();
                    // echo '<pre>'.$process->getData('indexer_code').': '.htmlentities(print_r($process->getStatus(),true)).'</pre>';
                    if($process->getStatus() == 'require_reindex')
                    $process->reindexEverything();







                    share|improve this answer















                    I liked Amit Bera's answer best - but modified placing the id's in an array and most importantly arranged for smoothest operation.
                    If you run straight through by the numbers re-indexing one index table can cause another to become invalid.
                    I.E. Index product_flat table then price can cause product flat table to become invalid and need re-indexing.



                    <?php
                    // this loops through all indexes and processes those that say they require reindexing

                    include_once 'app/Mage.php';

                    $mageRunCode = isset ( $_SERVER ['MAGE_RUN_CODE'] ) ? $_SERVER ['MAGE_RUN_CODE'] : '';
                    $mageRunType = isset ( $_SERVER ['MAGE_RUN_TYPE'] ) ? $_SERVER ['MAGE_RUN_TYPE'] : 'store';

                    $app = Mage::app ( $mageRunCode, $mageRunType );

                    $ids = array(13,9,8,7,6,1,2,3,5,4);

                    foreach($ids as $id)
                    $process = Mage::getSingleton('index/indexer')->getProcessById($id);
                    $state = $process->getStatus();
                    // echo '<pre>'.$process->getData('indexer_code').': '.htmlentities(print_r($process->getStatus(),true)).'</pre>';
                    if($process->getStatus() == 'require_reindex')
                    $process->reindexEverything();








                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jun 4 '15 at 11:49









                    dh47

                    1,68611431




                    1,68611431










                    answered Jun 4 '15 at 11:41









                    Dan TupperDan Tupper

                    11




                    11







                    • 2





                      FYI its @jim who answerd not amit.

                      – dh47
                      Jun 4 '15 at 11:50












                    • 2





                      FYI its @jim who answerd not amit.

                      – dh47
                      Jun 4 '15 at 11:50







                    2




                    2





                    FYI its @jim who answerd not amit.

                    – dh47
                    Jun 4 '15 at 11:50





                    FYI its @jim who answerd not amit.

                    – dh47
                    Jun 4 '15 at 11:50

















                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Magento Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f14828%2fcronjob-how-to-reindex-only-what-is-needed%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Magento 2 - Add success message with knockout Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Success / Error message on ajax request$.widget is not a function when loading a homepage after add custom jQuery on custom themeHow can bind jQuery to current document in Magento 2 When template load by ajaxRedirect page using plugin in Magento 2Magento 2 - Update quantity and totals of cart page without page reload?Magento 2: Quote data not loaded on knockout checkoutMagento 2 : I need to change add to cart success message after adding product into cart through pluginMagento 2.2.5 How to add additional products to cart from new checkout step?Magento 2 Add error/success message with knockoutCan't validate Post Code on checkout page

                    Fil:Tokke komm.svg

                    Where did Arya get these scars? Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Favourite questions and answers from the 1st quarter of 2019Why did Arya refuse to end it?Has the pronunciation of Arya Stark's name changed?Has Arya forgiven people?Why did Arya Stark lose her vision?Why can Arya still use the faces?Has the Narrow Sea become narrower?Does Arya Stark know how to make poisons outside of the House of Black and White?Why did Nymeria leave Arya?Why did Arya not kill the Lannister soldiers she encountered in the Riverlands?What is the current canonical age of Sansa, Bran and Arya Stark?