Insights

Dynamically Resolving Your ContentSearch Index

No Strings Attached

I was just chatting with some Sitecore colleagues and a question came up that they couldn't find an answer for. How do you dynamically select the active content search index?

This concept is key if your site supports master and web indexes (which it should).

You would take the half-hardcoded approach and do as follows:


// half-hardcoded index resolution

var indexName = String.Format("fishtank_{0}_index", Sitecore.Context.Database.Name);
var index = ContentSearchManager.GetIndex(indexName)

That's fine but what if you only have one index and need select between two differently named indexes like coveo_web_index and sitecore_master_index? What if you have many indexes?

Or what if a hardcoded string had broken your heart and you won't let yourself get hurt again?

Snippet for dynamic index resolution.


// Dynamic index resolution

var indexable = new SitecoreIndexableItem(Sitecore.Context.Item);
using (var context = ContentSearchManager.GetIndex(indexable).CreateSearchContext()) {
    …
}

Update. This is the original snippet from this post in 2014 for Sitecore 7. This please you the above in Sitecore 8.


// Dynamic index resolution in Sitecore 7

var indexable = Sitecore.Context.Item as SitecoreIndexableItem;
using (var context = ContentSearchManager.GetIndex(indexable).CreateSearchContext()) {
    …
}

No path of broken hearts here! Sorrow begone. Use your current item (or any item) to determine its content search index.

This post was authored using Markdown for Sitecore.

Meet Dan Cruickshank

President

Dan is the founder of Fishtank. He's a multi-time Sitecore MVP and Coveo MVP award winner. Outside of technology, he is widely considered to be a top 3 father (routinely receiving "Father of the Year" accolades from his family) and past his prime on the basketball court.

Connect with Dan