sitecore Search Delete all previous versions of the item in the index when adding new version


Example

By default Sitecore adds all versions of the item to the sitecore_master_index. The drawback of that is that if users are using workflows and adding lots of versions all of them will be added to the search results in the content editor.

Configuration:

<event name="item:versionAdded" >
              <handler type="FilterPatch.Library.ContentSearch.EventHandler, AssemblyName" method="Execute" />
       </event>

Handler implementation

public class EventHandler
    {
        public void Execute(object sender, EventArgs eventArgs)
        {
            var item = Event.ExtractParameter(eventArgs, 0) as Item;

            //If item has less than 2 versions - then skip
            if(item.Versions.Count < 2)
            {
                return;
            }

            var indexableItem = new SitecoreIndexableItem(item);

            var index = ContentSearchManager.GetIndex(indexableItem);

            using (var context = index.CreateDeleteContext())
            {
                foreach(var version in item.Versions.GetVersions(true))
                {
                    if(!version.Versions.IsLatestVersion())
                    {
                        var indexableItemVersion = new SitecoreIndexableItem(version);
                        context.Delete(indexableItemVersion.UniqueId);
                    }
                }
                context.Commit();                
            }
        }
    }