Get an item URL based on a search result

Version: 10.4

You can use search results to generate an item URL. This reduces database calls and allows rendering each search result with a link that takes site visitors to the associated content. This topic shows three different ways of getting an item URL.

Build an item URL based on the actual item

If you've retrieved the item in a search result, you can use Sitecore.Links.LinkManager.GetItemUrl to get the item URL.

To retrieve an item before building the URL:

  • Use the original GetItem method of SearchResultItem to get the item.

Alternatively, if you want to override a setting or add something to the SearchResultItem class, you can create a custom SearchResultItem class to meet those requirements, for example:

RequestResponse
    public class CustomSearchResultItem
    {
        

        [XmlIgnore]
        [IndexField(BuiltinFields.UniqueId)]
        [DataMember]
        [TypeConverter(typeof(IndexFieldItemUriValueConverter))]
        public virtual ItemUri Uri { get; set; }

        public virtual Item GetItem()
        { 
            if (this.Uri == null)
            {
                return null;
            }

            return Factory.GetDatabase(this.Uri.DatabaseName).GetItem(this.Uri.ItemID, this.Uri.Language, this.Uri.Version);
        }
    }

Then, use the GetItem method of the CustomSearchResultItem class to get the item:

RequestResponse
       IQueryable<CustomSearchResultItem> query = context.GetQueryable<CustomSearchResultItem>().Where(<conditions>);
       var actualItem = query.ToList().First().GetItem();

       BaseLinkManager linkManager = ...
       var options = linkManager.GetDefaultUrlBuilderOptions();
       // Populate parameters of 'options'

       var url = linkManager.GetItemUrl(actualItem, options);

To get an item URL from a computed index field:

  1. To enable the UrlLink computed index field, and store it in the urllink index field, create a configuration patch file and patch it to the App_Config\Include folder.

    RequestResponse
    <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/ 
    xmlns:search="http://www.sitecore.net/xmlconfig/search/">
      <sitecore role:require="Standalone or ContentManagement or ContentDelivery or SitecoreAI" search:require="solr">
        <contentSearch>
          <indexConfigurations>
            <defaultSolrIndexConfiguration>
              <documentOptions>
                <fields hint="raw:AddComputedIndexField">
                  <field fieldName="urllink" returnType="string" type=" Sitecore.ContentSearch.ComputedFields.UrlLink,Sitecore.ContentSearch" />
                </fields>
              </documentOptions>
            </defaultSolrIndexConfiguration>
          </indexConfigurations>
        </contentSearch>
      </sitecore>
    </configuration>
    Note

    You can use the siteName attribute to specify the site that will be used as a fallback if the site cannot be resolved by other means. Specifying siteName only works in single-site solutions, not in multisite solutions.

    After rebuilding indexes, indexed documents will have an additional urllink_s field which stores a link to this item.

  2. To access the URL in the search results, use a custom SearchResultItem class to access the URL, as long as the property has the [IndexField("urllink")] attribute, or the name of the property matches the name of the field value, that is, UrlLink.

    RequestResponse
    public
    class CustomSearchResultItem
        {
            
     
            [IndexField("urllink")]
            public virtual string Url
            {
                get;
                set;
            }
        }
  3. To access the indexed value, use the Url property of the CustomSearchResultItem class:

    RequestResponse
       IQueryable<CustomSearchResultItem> query = 
    context.GetQueryable<CustomSearchResultItem>().Where(<conditions>);
       var result = query.ToList();
       var -urlLink = result.First().Url;
    Note

    You can also use this field through the Url property of Sitecore.ContentSearch.SearchTypes.SearchResultItem to access the indexed value.

Implement a custom computed index field

If you need to have more control over how a link is generated, you can create a custom computed index field.

To implement a custom computed index field:

  1. Create a custom class such as CustomUrlLink, and register it in the index configuration.

    RequestResponse
    namespace <YOUR_NAMESPACE>.ComputedFields
    {
        public class CustomUrlLink: AbstractComputedIndexField
        {
              private readonly BaseLinkManager _linkManager;
    
                 ...
     
              public override object ComputeFieldValue(IIndexable indexable)
              {
                  Item item = indexable as SitecoreIndexableItem;
     
                  if (item == null)
                  {
                      return null;
                  }
    
                  var urlOptions = _linkManager.GetDefaultUrlBuilderOptions();
                  // Populate parameters of 'urlOptions'
     
                  return _linkManager.GetItemUrl(item, urlOptions);
              }
        }
    }
    RequestResponse
    <configuration xmlns:patch="http://www.sitecore.net/xmlconfig/"
    xmlns:role="http://www.sitecore.net/xmlconfig/role/" xmlns:search="http://www.sitecore.net/xmlconfig/search/">
      <sitecore role:require="Standalone or ContentManagement or ContentDelivery or SitecoreAI" search:require="solr">
        <contentSearch>
          <indexConfigurations>
            <defaultSolrIndexConfiguration>
              <documentOptions>
                <fields hint="raw:AddComputedIndexField">
                  <field fieldName="customurllink" returnType="string" type="<YOUR_NAMESPACE>.ComputedFields.CustomUrlLink,<YOUR_NAMESPACE>"/>
                </fields>
              </documentOptions>
            </defaultSolrIndexConfiguration>
          </indexConfigurations>
        </contentSearch>
      </sitecore>
    </configuration>

    After rebuilding indexes, indexed documents will have an additional customurllink_s field, which stores a link to this item.

  2. Create a CustomSearchResultItem class with a property that has an [IndexField("customurllink")] attribute, or a name that matches the name of the field value, that is, CustomUrlLink, to access the item URL.

    RequestResponse
        public class CustomSearchResultItem
        {
            
    
            [IndexField("customurllink")]
            public virtual string Url
            {
                get;
                set;
            }
        }
  3. You can now use the Url property of the CustomSearchResultItem class to access the indexed value.

    RequestResponse
       IQueryable<CustomSearchResultItem> query = context.GetQueryable<CustomSearchResultItem>().Where(<conditions>);
       var result = query.ToList();
       var customUrlLink = result.First().Url;
    

Do you have some feedback for us?

If you have suggestions for improving this article,