3

I have issue with missing some products on frontend.
I noticed that reindexig catalog_product_category is fixing this issue.
In observer triggered after import I just add reindexing script:

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $productId = $observer->getEvent()->getId();
    $this->getIndexer(\Magento\Catalog\Model\Indexer\Product\Category::INDEXER_ID)->reindexRow($productId);
    return $this;
}

/**
 * @param string $indexerId
 * @return \Magento\Framework\Indexer\IndexerInterface
 */
protected function getIndexer($indexerId)
{
    return $this->indexerFactory->create()->load($indexerId);
}

Importing script changes products one by one.
Unfortunately this doesn't works fine. However if I do:

 public function execute(\Magento\Framework\Event\Observer $observer)
{
    $this->getIndexer(\Magento\Catalog\Model\Indexer\Product\Category::INDEXER_ID)->reindexAll();
    return $this;
}

it will reindex all catalog_product_category for every imported product.
Is it possible to reindex one product?
Generally first script should works fine, but it doesn't - all imported products are missing.

1
  • can you add the path for indexerFactory ? Commented Jul 16, 2021 at 0:53

1 Answer 1

4

You can use something like

    public function reindexByProductsIds($productIds, $indexLists)
    {
        foreach($indexLists as $indexList) {
            $categoryIndexer = $this->indexerRegistry->get($indexList);
            if (!$categoryIndexer->isScheduled()) {
                $categoryIndexer->reindexList(array_unique($productIds));
            }
      }
}

where $indexLists is an array like ['catalog_product_category', 'catalog_product_attribute']

7
  • Please notice that reindexRow() at the end will call the same function as reindexList(). One difference is that reindexRow makes array from one product Id before call it. Commented Nov 30, 2017 at 15:46
  • Indeed, for your product you can use reindexRow instead of reindexList.
    – Vinz
    Commented Dec 1, 2017 at 10:39
  • Exactly, but there is still a problem and I dont know how can I debug it. Add logs deeply into indexer? It happens on production only. Commented Dec 1, 2017 at 11:47
  • Have you got some log yet or nothing ? If not, yes you can add some deeply.
    – Vinz
    Commented Dec 5, 2017 at 15:19
  • in your example which class are instantiated in $this->indexerRegistry? I used Magento\Indexer\Model\IndexerFactory in my case but i want to try also your solution Commented Jun 18, 2019 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.