Sunday, March 13, 2022

Computed index for item url in Sitecore

 Normally, sitecore will not index the item url in Solr. We may need to create a computed index for the same, 

However, the challenge is that when we try to generated the url using Link Manager, system would throw "object reference not set to an instance of an object" error, as the Site and Item context is not available during computed index execution. 

So, in order to get the url indexed, we should follow the below steps,

Code:

        public object ComputeFieldValue(IIndexable indexable)
        {
            Item sitecoreItem = indexable as SitecoreIndexableItem;
            if (sitecoreItem == null)
                return null;
            if (sitecoreItem.TemplateName != "<templatename>")
                return null;
            var siteContext = SiteContextFactory.GetSiteContext("<sitename>");
            Sitecore.Context.Site = siteContext;
            Sitecore.Context.Item = sitecoreItem;
            ItemUrlBuilderOptions itemUrlBuilder = new ItemUrlBuilderOptions
            {
                SiteResolving = true,
                AlwaysIncludeServerUrl = false,
                LowercaseUrls = true
            };
            var articleUrl = LinkManager.GetItemUrl(sitecoreItem, itemUrlBuilder);
            return articleUrl;

        }


Config:

<?xml version="1.0"?>

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">

<sitecore>

<contentSearch>

<indexConfigurations>

<defaultSolrIndexConfiguration>

<fieldMap>

<fieldNames hint="raw:AddFieldByFieldName">

<field fieldName="ArticleUrl" returnType="string" />

</fieldNames>

</fieldMap>

<documentOptions>

<fields hint="raw:AddComputedIndexField">

<field fieldName="ArticleUrl" returnType="string">

<<ClassFullyQualifiedName>>.<<AssemblyName>>

</field>

</fields>

</documentOptions>

</defaultSolrIndexConfiguration>

</indexConfigurations>

</contentSearch>

</sitecore>

</configuration>


No comments: