Following with my latest post about Add Custom Items to Sitecore Solr here I’m gonna explain how to delete those custom items.
The first step is Querying those items
List<AddEventSearchModel> docHits;
using (var context = ContentSearchManager.GetIndex("desired_index_name").CreateSearchContext())
{
var filterPredicate = PredicateBuilder.Create<CustomSearchModel>(x => x.TemplateId == new ID("{9843569E-C37A-434B-942B-92DBAACEC619})");
var query = context.GetQueryable<CustomSearchModel>()
.Where(filterPredicate);
var results = query.GetResults();
docHits = results.Hits.Select(x => x.Document).ToList();
}
Once you get the list of items, let’s go to the delete process
var solr = ContentSearchManager.GetIndex("desired_index_name");
using (new SecurityDisabler())
{
docHits.ForEach(x =>
{
IndexCustodian.DeleteItem(solr, (SitecoreItemId)x.Id);
});
if(IndexCustodian.IsIndexingPaused(solr))
IndexCustodian.ResumeIndexing();
}
Why use IndexCustodian instead of solr.Operations.Delete, the reasons are:
More information here in the Sitecore documentation
When you invoke these methods directly on theISearchIndex
interface, it can cause various issues ranging from missing log entries to application crash due to aStackOverflowException
exception. Therefore, use these API calls from theIndexCustodian
class. When you use theIndexCustodian
class, the following things are different from theISearchIndex
interface:
TheIndexCustodian
class runs the index operation in the context of a job. This ensures that the operation is atomic: no other rebuild or update operations can run for the same search index simultaneously.
TheIndexCustodian
class triggers theindexing:start
andindexing:end
events. Sitecore relies on the events to keep instances in sync, and it also uses events to process some local changes.
Hope this can help you in any way.
Happy coding!