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.



Content of indexer.xml

<?xml version="1.0"?>
<config xmlns:xsi="" 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>

Create Mview configuration file 

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



Content of mview.xml file

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

Create Indexer class

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



Content of Indexer.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.




Related Posts
  1. How to create new admin user in Magento 2
  2. How to add an custom attribute in Magento 2
  3. How To Add Simple Product in Magento 2
  4. How to add a related products in the product page Magento 2
Related Products