Magento – Magento2 prevent reindex after adding product programmatically

indexingmagento2productsreindex

I have made a module that adds a grouped product to the catalog. After adding some products I always have to reindex to see the changes. If I add a product via the Admin, this does not seem to be necessary.

Is there a way to only update the indexes for the added product instead of having to update all product indexes?

I have pasted the code I use to add a product below:

$product = $this->objectManager->create('\Magento\Catalog\Model\Product');
$product->setSku($iceProduct['sku']) // Set your sku here
    ->setName($iceProduct['title']); // Name of Product
    ->setDescription($iceProduct['descr_long']); // Name of Product
 //enz...
    ->save();

Best Answer

  1. inject \Magento\Indexer\Model\IndexerFactory to the __construct method
  2. instantiate it as class variable ($this->_indexerFactory right now)
  3. run the following code after saving product:

foreach ([ /* feel free to delete indexers which not require reindexing */ 'catalog_category_product', 'catalog_product_category', 'catalog_product_price', 'catalog_product_attribute', 'cataloginventory_stock', 'catalogrule_rule', 'catalogrule_product', 'catalogsearch_fulltext',
] as $indexerId) { $indexer = $this->_indexerFactory->create() ->load($indexerId) ->reindexRow($product->getId()); //->reindexAll(); // <= use it to reindex whole everithing }

Related Topic