December 18, 2014 11:18 by
Peter
During my recents projects in Kentico 8.1, I had to tack together the search engine to own search fields on the web site. The search engine included in Kentico is Lucene, a full text search engine supported physical files indexes. For every web site, you wish to build on rebuild basis the different search indexes you define in Kentico. During this case, I assumed that the regular Task "Optimize search indexes", defined by default in Kentico, was doing this calculation of search indexes. My assumption was wrong, there's actually no regular task doing the index rebuilding.
So, because we did not wish to log every night to my sites to launch manually each index rebuilding, I enforced my own scheduled task for doing it, here is the source code :
using System;
using CMS.EventLog;
using CMS.Scheduler;
using CMS.SiteProvider;
using System.Data;
namespace MyProject.Services.ScheduledTasks
{
public class SmartSearchReIndexTask: ITask
{
private const string Name = "SmartSearchReIndexTask";
public string Execute(TaskInfo task)
{
var response = " Reindexing smart search updated successfully.";
const string eventCode = "Smart Search Execution";
try
{
//retrieve Planet search indexes
EventLogProvider.LogInformation(Name, eventCode, "Start reindexing");
DataSet indexes = SearchIndexInfoProvider.GetSearchIndexes("IndexName LIKE N'MyProject%'", null);
if (indexes != null)
{
foreach (DataTable table in indexes.Tables)
{
foreach (DataRow row in table.Rows)
{
//create a reindex task for that search index
SearchIndexInfo searchIndexInfo = SearchIndexInfoProvider.GetSearchIndexInfo(Convert.ToInt32(row.ItemArray[0]));
//row.ItemArray[0] is the SearchIndex ID
if (searchIndexInfo != null)
{
SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Rebuild, searchIndexInfo.IndexType, null, searchIndexInfo.IndexName);
System.Threading.Thread.Sleep(100);
EventLogProvider.LogInformation(Name, eventCode, string.Format("Recalculating the index: {0}", searchIndexInfo.IndexName));
}
}
}
}
EventLogProvider.LogInformation(Name, eventCode, response);
}
catch (Exception ex)
{
response = "Error reindexing smart search . Check the event log for more information.";
EventLogProvider.LogException(Name, eventCode, ex);
}
return response;
}
}
}
Put this code in a library, put this library in the bin folder of your Kentico 8.1 site and then configure a new custom task.