Which Sitecore Index to use?

I was asked an interesting question the other day:

Why are my components not working in the Page Editor?

This puzzled me for a bit, the Page Editor was not preventing editing of the content, however the content was not being saved back into Sitecore. However, if the content was modified directly in the Content Editor, everything was fine.

So, what was going on?

Upon closer inspection of the code, it appeared that a the Sitecore ContentSearch was being used to pull content from the Index – but the index being used was “sitecore_web_index”.


ISearchIndex searchIndex = Sitecore.ContentSearch.ContentSearchManager.GetIndex("sitecore_web_index");

When this happens, creating a SearchContext, performing a search and calling GetItem() on a SearchResultItem will pull the item out of the Web database. This is fine, however as the items are coming from the Web database, this will not play nicely with the Page Editor.

A “quick ‘n’ dirty” method of getting around this is to look at the Context database to see whether you should be using the Master index or Web index. Below is a static helper to decide which index you should be looking at:

public static string GetIndex()
{
    // TODO - Find a way of getting the database associated with the Datasource
    switch (Sitecore.Context.Database.Name)
    {
        case ("master"):
            return "sitecore_master_index";
        default:
            return "sitecore_web_index";
    }
}

Then, simply use this static function in your code instead of naming the index directly:

ISearchIndex searchIndex = Sitecore.ContentSearch.ContentSearchManager.GetIndex(SitecoreJim.Utilities.Index.GetIndex());

Yes, this is quick and dirty – just wanted to get this out there to help others, however you get the concept 🙂

Upon doing a quick google search, I also found this post by The Grumpy Coder which discusses the same thing.

Hope this helps someone!

Advertisements

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