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.

👋 Hey Sitecore Enthusiasts!

Sign up to our bi-weekly newsletter for a bite-sized curation of valuable insight from the Sitecore community.

What’s in it for you?

  • Stay up-to-date with the latest Sitecore news
  • New to Sitecore? Learn tips and tricks to help you navigate this powerful tool
  • Sitecore pro? Expand your skill set and discover troubleshooting tips
  • Browse open careers and opportunities
  • Get a chance to be featured in upcoming editions
  • Learn our secret handshake
  • And more!
Sitecore Snack a newsletter by Fishtank Consulting
 

Meet Dan Cruickshank

President | Sitecore MVP x 11

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