Wednesday 1 December 2010

Updating indexes on a web farm

Well there is loads of information on this in other blogs. Most refer to the history engine. In principle this works well, but if you want all the servers to present the same content, then this is not always reliable. I have created a service on each server that is called on the publish event that will update the index. You will need to force the service to log in as an admin user.


[WebMethod(Description = "Rebuilds index on webserver", EnableSession = true)]
        public bool UpdateIndex(string itemUri)
        {
            try
            {
                Log.Warn("Update Indexes WS command reached.", this);

                Database webDB = Factory.GetDatabase("web");

                Item item = webDB.GetItem(itemUri);
                if (item != null)
                {
                    string username = Sitecore.Configuration.Settings.GetSetting("admin");
                    string password = Sitecore.Configuration.Settings.GetSetting("b");
                    Sitecore.Security.Authentication.AuthenticationManager.Login(username, password);
                    for (int i = 0; i < webDB.Indexes.Count; i++)
                    {
                        //Sitecore.Data.Indexing.Index index = new Index(webDB.Indexes[i].Name);
                        webDB.Indexes[i].UpdateItem(item);
                        Log.Audit(this, "Update search index: {0}", new string[] { webDB.Indexes[i].Name });
                    }
                }

                Log.Warn("Update Indexes completed by WS", this);
                return true;
            }
            catch (Exception ex)
            {
                Log.Error(string.Format("Update Indexes Failed: {0}", ex.Message), this);
                return false;
            }
        }