Magento – Magento 2 – How to reindex one product

indexingmagento2productreindex

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.

Best Answer

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']