Include templates dynamically based on Sitecore field values in your SOLR index

In one of our projects, we had the need to create a separate index only for items of a certain set of templates – and the content admin needed to have the flexibility to edit this list of templates.

If this was only a question of including / excluding templates in the search, it would be a much better solution to just allow the content author to select a set of templates on a multilist field on a settings item some place.
However, from a performance perspective – this was the solution we definitely needed considering our content structure, and content editing process.

Here’s how we did it –

We added a field on /sitecore/templates/System/Templates/Template called ‘Exclude From Search Index’
We created a custom crawler then, to check this field on the item template, before adding it to the index. Do ensure you use this crawler only on non-sitecore system indexes to avoid Sitecore responding in an unexpected way.

using Foundation.Search.Models.sitecore.templates.Foundation.Search;
using Sitecore.ContentSearch;
using Sitecore.Data.Items;

namespace Foundation.Search.Solr.Crawlers
{
    public class SearchIndexCrawler : SitecoreItemCrawler
    {
        protected override bool IsExcludedFromIndex(SitecoreIndexableItem indexable, bool checkLocation = false)
        {
            bool isExcluded = base.IsExcludedFromIndex(indexable, checkLocation);

            if (isExcluded)
                return true;

            Item item = indexable;
            return item.Template.InnerItem[I_Indexing_SettingsConstants.Exclude_From_Search_IndexFieldName] == "1";
        }

        protected override bool IndexUpdateNeedDelete(SitecoreIndexableItem indexable)
        {
            Item item = indexable;
            return item.Template.InnerItem[I_Indexing_SettingsConstants.Exclude_From_Search_IndexFieldName] == "1";
        }
    }
}

You can then use this crawler in your site index:


web
/sitecore

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 )

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s