How to Indexing and Reindex in Magento 2 programmatically

Follow the following steps to create a custom indexer in Magento 2:

  • Create the Indexer configuration file
  • Create Mview configuration file
  • Create Indexer class

Create the Indexer Configuration file

The indexer will be defined in the indexer.xml file.

Directory

app/code/VendorName/ModuleName/etc/indexer.xml

Content of indexer.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Indexer/etc/indexer.xsd">
    <indexer id="vendorname_modulename_indexer" view_id="vendorname_modulename_indexer" class="VendorName\ModuleName\Model\Indexer\Indexer">
        <title translate="true">Custom Indexer</title>
        <description translate="true">Custom indexer in magento 2</description>
    </indexer>
</config>

Create Mview configuration file 

The mview.xml file is used to handle the database changes for some entities.

Directory

app/code/VendorName/ModuleName/etc/mview.xml

Content of mview.xml file

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Mview/etc/mview.xsd">
    <view id="vendorname_modulename_indexer" class="VendorName\ModuleName\Model\Indexer\Indexer" group="indexer">
        <subscriptions>
            <table name="catalog_product_entity" entity_column="entity_id" />
        </subscriptions>
    </view>
</config>


Create Indexer class

  • Create the indexer class as indexer.php in model.

Directory

app/code/VendorName/ModuleName/Model/Indexer/Indexer.php

Content of Indexer.php

<?php
namespace VendorName\ModuleName\Model\Indexer;

class Indexer implements \Magento\Framework\Indexer\ActionInterface, \Magento\Framework\Mview\ActionInterface
{
/*
* Used by mview, allows process indexer in the "Update on schedule" mode
*/
public function execute($ids){

//code here!
}

/*
* Run all the data and reindex
* Run when reindex via command line
*/
public function executeFull(){
//code here!
}
/*
* Works with a set of entities changed (maybe mass-action)
*/
public function executeList(array $ids){
//code here!
}
/*
* Works in runtime for a single entity using plugins
*/
public function executeRow($id){
//code here!
}
}

Run Reindex by command

You can run the indexer by following this command:

php bin/magento indexer:reindex

 

 

when we need to index or reindex in Magento to we need to run a few commands. To get rid of the running command again and again just add Magneto 2 reindex extension for free and do index/reindex with a single click in magneto admin index management.