How to rebuild custom solr index programmatically in Sitecore
Hey, there! Welcome to "Sitecore Series"
Post is all about sharing the details regarding custom index rebuild through code.
Sitecore rebuilds indexes data but it does not rebuild indexes very frequently, all depends on the indexing strategies specified for that index.
In Sitecore, we have an option to rebuild indexes under control panel and the index rebuild can be performed manually but if we want the index to be rebuild after some operation is done or after some time span? Let's achieve this through scheduler.
Create a scheduler to perform index rebuild operation.
1) scheduler:
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Tasks;
namespace Testing.Feature.Testing.Scheduler
{
public class TestIndexRunScheduler
{
public void Execute(Item[] items, CommandItem command, ScheduleItem scheduleItem)
{
try
{
//Rebuild Index
//Fetch the index to perform rebuild operation
Sitecore.ContentSearch.ISearchIndex index = Sitecore.ContentSearch.ContentSearchManager.GetIndex("customtest_master_index");
if (index != null)
{
//add logic if required and rebuild index only when the conditions are met
index.Rebuild(Sitecore.ContentSearch.IndexingOptions.ForcedIndexing);
}
Log.Info("Custom index rebuild completed through scheduler", "");
}
catch (System.Exception ex)
{
//Log exception.....
}
}
}
}
deploy the code to "Webroot" and follow below steps to create scheduler definition in CMS and reference our scheduler created in earlier step.
2) Creating Command:
Path: /sitecore/system/Tasks/Commands/
Create a command item under this path and fill the type and method.
Type: class created in step1, namespace (ex: Testing.Feature.Testing.Scheduler,TestIndexRunScheduler, Testing.Feature.Testing)
Method: Execute
For Schedule Time, if you are not sure about the format and how to specify. Just right click on schedule ->selects Scripts - > edit schedule and a pop up will open with details.
3) Creating Schedule:
For Schedule Time, if you are not sure about the format and how to specify. Just right click on schedule ->selects Scripts - > edit schedule and a pop up will open with details.
Just add the details as per your requirement, refer below screenshot for details:
Once the schedule is created, rebuild index operation will be performed as per the configuration set in schedule.
After index rebuild, it will show the time of last run in the "Last run" field of schedule (created in step3)
Hope this post helps you. Happy Sitecoring... 😊
Comments
Post a Comment