Recently we faced an interesting problem. We were updating a Sitecore item field but after publish that was not reflecting in the search results. Our search results are coming from the index. If we rebuild the index then it was getting updated. But we have thousands of items in the index and the rebuild the whole index was taking a lot of time. However, our challenge is, we want to update a Sitecore item then publish it, and without rebuilding the whole index, we want to see the update in the index.

There could be many different ways to resolve this issue. But we followed a couple of simple steps. Firstly, we figured out, how we can update a single record in the index. Secondly, we executed this while we publish the Sitecore item.

In the backend, we get the Sitecore item from Context, and from the item, we get the SitecoreItemUniqueId. Then we get the index using ContentSearchManager. Now, update the record in the index by calling IndexCustodian.UpdateItem.

var item = context.PublishOptions.TargetDatabase.GetItem(context.ItemId);
var uniqueId = new SitecoreItemUniqueId(item?.Uri);
var webContentIndex = ContentSearchManager.GetIndex(IndexName);

IndexCustodian.UpdateItem(webContentIndex, uniqueId);
.

Every time we do a publish in Sitecore, it executes an event named “publish:itemProcessed“. We implement a hander and hook into this event. This handler is now executing our above code and update a single index record each time we update an item and publish it. Handler code:

namespace XYZ.Foundation.Indexing.Events
{
    public class ItemProcessedProcessor
    {
        public void ItemProcessed(object sender, EventArgs args)
        {
            ItemProcessedEventArgs itemProcessedEventArgs = args as ItemProcessedEventArgs;
            PublishItemContext context = itemProcessedEventArgs != null ? itemProcessedEventArgs.Context : null;
		}
	}
}

Following is the Sitecore patch for the event handler.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
	<sitecore>
		<events>
			<event name="publish:itemProcessed">
				<handler type="XYZ.Foundation.Indexing.Events.ItemProcessedProcessor, XYZ.Foundation.Indexing" method="ItemProcessed"/>
			</event>
		</events>
	</sitecore>
</configuration>

Thanks
Munir

Previous post Send alert when Sitecore running jobs get stuck
Next post Dialogflow Custom Payload for Facebook Messenger

Leave a Reply

Your email address will not be published.