I just need to reset all indexing programmatically without use of command. Is there any way to do this . Any idea please share.
3 Answers
You can reset the state of index by below code
public function __construct(\Magento\Indexer\Model\Indexer\CollectionFactory $indexerCollectionFactory)
{
$this->indexerCollection = $indexerCollectionFactory;
}
public function resetIndexer()
{
$indexers = $this->indexerCollection->create()->getItems();
/** @var \Magento\Framework\Indexer\IndexerInterface $indexer */
foreach ($indexers as $indexer) {
try {
$indexer->getState()
->setStatus(\Magento\Framework\Indexer\StateInterface::STATUS_INVALID)
->save();
} catch (\Exception $e) {
//catch exception
}
}
}
I know this is too late Please see - PHP file to reindex reset and view status of indexer
https://github.com/estvivek/External_magento_2_reindex_reset
https://github.com/estvivek/External_magento_2_reindex_reset/tree/master/subfolder will enable reset for failed indexers only rest of the features are same.
disclaimer - It was created for one of our websites and code is in my Github account.
An improvement of the solution by MeenakshiSundaram R :
In Magento 2.3 you can now call $indexer->invalidate();
that will do the work for you :
/**
* Set indexer invalid
*
* @return void
*/
public function invalidate()
{
$state = $this->getState();
$state->setStatus(StateInterface::STATUS_INVALID);
$state->save();
}