Excluding an item/page from search or index

This is a generic situation most of Sitecore geeks face during their development work. Though, you may find several solutions over the internet, but what I am going to put here is the most simple and robust solution.

Just a checkbox and few lines of code and you are done. Let’s do it now.

  1. add a checkbox field on the item template or on the base template ( your choice) , name it something meaningful like “ExcludeFromSearch” or “DoNotIndex”
  2. Create a custom item crawler. see the code below
    using Sitecore.ContentSearch;
    using Sitecore.Data;
    using Sitecore.Data.Items;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    namespace Learning.Framework.Search.Indexing.Crawler
    {
    public class CustomItemCrawler : SitecoreItemCrawler
    {
    protected override bool IsExcludedFromIndex(SitecoreIndexableItem
    indexable, bool checkLocation = false)
    {
    var isExcluded = base.IsExcludedFromIndex(indexable, checkLocation);
    if (isExcluded)
    return true;
    Item item = indexable;return (item[new ID(pass the checkbox field id here)] == "1") ? true: false;
    }
    protected override bool IndexUpdateNeedDelete(SitecoreIndexableItem
    indexable)
    {
    var needDelete = base.IndexUpdateNeedDelete(indexable);
    if (needDelete)
    return true;
    Item item = indexable;
    return (item[new ID(pass the checkbox field id here)] == "1") ? true:
    false;
    }
    }
    }
  3. Patch the above custom crawler to the config as shown belowExcludeFromSearch-config
  4. Build the solution and publish to the server. Check the checkbox on whichever item you want to exclude/remove from search.
  5. Once publish is done, rebuild the target index from control panel and you are done.

Note: There is a method in the above CustomItemCrawler , the method name is IndexUpdateNeedDelete

this is to delete the existing items/pages from the index.

I hope this post will help some of you.

Happy Coding !!!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s