Hello magento friends todays in this blog post im share with you to How to Create Custom Indexer in Magento 2?
Creating a custom indexer in Magento 2 involves several steps. An indexer in Magento 2 is responsible for updating and managing the data in the database to improve the performance of your store. Follow the steps below to create a custom indexer in Magento 2:
Step 1: Create a new module
Create a new Magento 2 module to contain your custom indexer. If you are not familiar with creating a new module in Magento 2, you can refer to the official documentation or use an online module creator tool.
Step 2: Define indexer configuration
In your module, create a file etc/indexer.xml to define the configuration of your custom indexer. This file tells Magento how to process and update the data for your custom index. Here's an example of indexer.xml:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Indexer/etc/indexer.xsd">
<indexer id="your_custom_indexer" view_id="your_custom_indexer" class="[Vendor]\[Module]\Model\Indexer" index_by_schedule="false"/>
</config>
Step 3: Create the indexer class
Create a model class for your custom indexer. This class should be located at [Vendor]/[Module]/Model/Indexer.php and should implement the \Magento\Framework\Indexer\ActionInterface interface. This interface contains the necessary methods to update and retrieve the index data.
<?php
namespace [Vendor]\[Module]\Model;
use Magento\Framework\Indexer\ActionInterface;
use Magento\Framework\Mview\ActionInterface as MviewActionInterface;
class Indexer implements ActionInterface, MviewActionInterface
{
// Implement the necessary methods for indexing here
// The most important methods are `executeFull()` and `executeRow()`
}
Step 4: Define indexers in di.xml
Next, you need to define your indexer class in the di.xml file to make Magento aware of it. Create a file [Vendor]/[Module]/etc/di.xml and add the following content:
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Framework\Indexer\IndexerInterface">
<arguments>
<argument name="indexers" xsi:type="array">
<item name="your_custom_indexer" xsi:type="object">[Vendor]\[Module]\Model\Indexer</item>
</argument>
</arguments>
</type>
</config>
Step 5: Run setup upgrade
After creating the module and defining the custom indexer, run the following command to update the Magento setup:
php bin/magento setup:upgrade
Step 6: Reindex
Finally, you can now reindex your custom indexer using the following command:
php bin/magento indexer:reindex your_custom_indexer
That's it! Your custom indexer should now be working, and you can customize the indexing logic inside the Indexer.php class as per your requirements. Remember to replace [Vendor] and [Module] with your actual vendor and module names.