Mike Robbins

Sitecore Developer Blog

Follow me on GitHub

Text Based Content Search Based On Tagging

Out of the box Sitecore offers Content Editors the power to create tags, and assign them to content items using the Tagging field in standard values.

Tagging Standard Value

Tagging Standard Value>

When analysing the indexes using LUKE, you can see that Sitecore indexes the ID's of each tag. This makes it difficult to perform a text based content search that also matches on tags.

Luke Index View

Luke Index View

However Sitecore gives us the power to create computed fields in search indexes. This means we can create new fields within the index and programmatically create text into the index.

This example below uses a computed field that instead of indexing the ID of the tag, instead adds the item name of each tag seperated by a space. This then allows you to perform a text based search against the tag. (Sitecore by default indexes the __Semantics field, so here i'm creating a new field in the index called "tags" not to override any standard Sitecore functionality)

 

Computed Field Class

namespace MikeRobbins.CMS.ComputedFields<br />
{
  public class Tags : IComputedIndexField<br />
  {
    public object ComputeFieldValue(Sitecore.ContentSearch.IIndexable indexable)
    {
      var tags = new StringBuilder();
      Item obj = (Item)(indexable as SitecoreIndexableItem);
      if (obj != null)
      {
        var tagField = (Sitecore.Data.Fields.MultilistField)obj.Fields["__Semantics"];
        if (tagField != null)
        {
          var items = tagField.GetItems();
          foreach (var item in items)
          {
            tags.Append(item.Name + " ");
          }
        }
      }
      return tags.Length != 0? tags.ToString():null;
    }
    public string FieldName { get; set; }
    public string ReturnType { get; set; }
  }
}

XML Config

Add this XML to the "AddComputedIndexField" section of your search index config.

<field fieldName="tags" >MikeRobbins.CMS.ComputedFields.Tags,MikeRobbins.CMS</field>