DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on • Edited on

How To: reindex customers after writing directly to `customer_entity` table

In magento2.x development sometimes speed is crucial. Therefore directly accessing database and writing into tables can save lots of time.

Assuming we need to update a record for a customer eg for setting a default group id:

 /**
  * @var $resource \Magento\Framework\DB\Adapter\Pdo\Mysql\Interceptor
  */
$default_customer_group_id=1
$customerIds = [1,2,111,444];

$resource->update('customer_entity'
['group_id'=>$default_customer_group_id],
  ['entity_id in (?)'=>$customerIds,]
);
Enter fullscreen mode Exit fullscreen mode

The code above will update the customers But it won't update customer indexes in elasticsearch (or opensearch) therefore we have to update by ourselves:

/**
 * @var $indexerFactory Magento\Framework\Indexer\IndexerInterfaceFactory
 */
 $indexer = $indexerFactory->create();
 $indexer->load('customer_grid');
 $indexer->reinderList($customerIds);
Enter fullscreen mode Exit fullscreen mode

But How On earth I will get an instance of IndexerInterfaceFactory tbw?

It can be either using ObjectManager:

$objectManager = ObjectManager::getInstance();
$indexerFactory = $objectManager->create(\Magento\Framework\Indexer\IndexerInterfaceFactory::class);
Enter fullscreen mode Exit fullscreen mode

Or via dependency injection upon your constructor:


use \Magento\Framework\Indexer\IndexerInterfaceFactory;

// class Definition here

private $indexer;

public function __construct(
        // Rest of services here
        IndexerInterfaceFactory $indexerFactory
    ) {

        $this->indexer=$indexerFactory->create();
        $this->indexer->load('customer_grid');
    }

Enter fullscreen mode Exit fullscreen mode

Magento 2 uses for any class Dependency Injection. Furthermore it auto-injects any class to the constructor as well.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay