Skip to content

Delete Custom Items in Sitecore Solr

Posted in :

rbatallas

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 the ISearchIndex interface, it can cause various issues ranging from missing log entries to application crash due to a StackOverflowException exception. Therefore, use these API calls from the IndexCustodian class. When you use the IndexCustodian class, the following things are different from the ISearchIndex interface:

The  IndexCustodian 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.

The  IndexCustodian class triggers the indexing:start and indexing: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!

Leave a Reply

Your email address will not be published. Required fields are marked *